Help us shape the future of Go! Take the 2026 Go Developer Survey

types

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 5 Imported by: 6

Documentation

Overview

Package types defines all domain data types for the OpenShell SDK v1 API.

These types are the canonical definitions used by both the client layer (openshell/v1) and the converter layer (openshell/v1/internal/converter). The v1 package re-exports all types via type aliases for backward compatibility.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyApproveAllOptions

func ApplyApproveAllOptions(opts []ApproveAllOption) approveAllConfig

ApplyApproveAllOptions applies options and returns the config.

func ApplyCreateOptions

func ApplyCreateOptions(opts []CreateOption) createConfig

ApplyCreateOptions applies options and returns the config. Nil options are ignored so that callers migrating from the positional labels parameter, which they passed as nil for an unlabeled sandbox, do not panic.

func ApplyGetDraftOptions

func ApplyGetDraftOptions(opts []GetDraftOption) getDraftConfig

ApplyGetDraftOptions applies options and returns the config.

func ApplyGetStatusOptions

func ApplyGetStatusOptions(opts []GetStatusOption) getStatusConfig

ApplyGetStatusOptions applies options and returns the config.

func ApplyListPolicyOptions

func ApplyListPolicyOptions(opts []ListPolicyOption) listPolicyConfig

ApplyListPolicyOptions applies options and returns the config.

func ApplyLogOptions

func ApplyLogOptions(opts []LogOption) logConfig

ApplyLogOptions applies options and returns the config.

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists returns true if the error indicates a resource already exists.

func IsCancelled

func IsCancelled(err error) bool

IsCancelled returns true if the error indicates the operation was cancelled.

func IsConflict

func IsConflict(err error) bool

IsConflict returns true if the error indicates a conflict, such as optimistic concurrency or an invalid state transition.

func IsDeadlineExceeded

func IsDeadlineExceeded(err error) bool

IsDeadlineExceeded returns true if the error indicates a deadline was exceeded.

func IsInvalidArgument

func IsInvalidArgument(err error) bool

IsInvalidArgument returns true if the error indicates an invalid argument.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error indicates a resource was not found.

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied returns true if the error indicates insufficient permissions.

func IsUnauthenticated

func IsUnauthenticated(err error) bool

IsUnauthenticated returns true if the error indicates invalid or missing credentials.

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable returns true if the error indicates the service is unavailable.

func IsUnimplemented

func IsUnimplemented(err error) bool

IsUnimplemented returns true if the error indicates the operation is not implemented.

Types

type AddAllowRules

type AddAllowRules struct {
	// Target is required and declares the full scope affected by the append.
	Target *L7RuleTarget
	// Rules are the allow rules to append.
	Rules []L7Rule
}

AddAllowRules appends layer-7 allow rules to a specific endpoint.

type AddDenyRules

type AddDenyRules struct {
	// Target is required and declares the full scope affected by the append.
	Target *L7RuleTarget
	// DenyRules are the deny rules to append.
	DenyRules []L7DenyRule
}

AddDenyRules appends layer-7 deny rules to a specific endpoint.

type AddNetworkRule

type AddNetworkRule struct {
	// RuleName is the name key for the rule.
	RuleName string
	// Rule is the full network policy rule to add.
	Rule NetworkPolicyRule
}

AddNetworkRule adds a named network policy rule with a full rule definition.

type ApproveAllOption

type ApproveAllOption func(*approveAllConfig)

ApproveAllOption configures an ApproveAllDraftChunks call.

func WithDraftApprovals

func WithDraftApprovals(approvals ...DraftChunkApproval) ApproveAllOption

WithDraftApprovals supplies the exact reviewed chunk tokens for bulk approval.

func WithIncludeSecurityFlagged

func WithIncludeSecurityFlagged() ApproveAllOption

WithIncludeSecurityFlagged includes security-flagged chunks in bulk approval.

type ApproveAllResult

type ApproveAllResult struct {
	// PolicyVersion is the new policy version after merge.
	PolicyVersion uint32
	// PolicyHash is the SHA-256 hash of the new policy.
	PolicyHash string
	// ChunksApproved is the number of chunks approved.
	ChunksApproved uint32
	// ChunksSkipped is the number of chunks skipped (security-flagged).
	ChunksSkipped uint32
}

ApproveAllResult contains the result of approving all draft chunks.

type ApproveResult

type ApproveResult struct {
	// PolicyVersion is the new policy version after merge.
	PolicyVersion uint32
	// PolicyHash is the SHA-256 hash of the new policy.
	PolicyHash string
}

ApproveResult contains the result of approving a single draft chunk.

type AttachProviderResult

type AttachProviderResult struct {
	Sandbox  *Sandbox
	Attached bool
}

AttachProviderResult holds the result of attaching a provider to a sandbox.

type AuthProvider

type AuthProvider interface {
	GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
	RequireTransportSecurity() bool
}

AuthProvider supplies per-RPC credentials. It implements the grpc credentials.PerRPCCredentials interface.

type ClearResult

type ClearResult struct {
	// ChunksCleared is the number of chunks cleared.
	ChunksCleared uint32
}

ClearResult contains the result of clearing all draft chunks.

type ComputeDriverInfo

type ComputeDriverInfo struct {
	Name          string
	DriverName    string
	DriverVersion string
}

ComputeDriverInfo describes a compute backend available on the gateway.

type Config

type Config struct {
	Address     string
	TLS         *TLSConfig
	Auth        AuthProvider
	Timeout     time.Duration
	RetryPolicy *RetryPolicy
	Logger      Logger
}

Config holds all settings needed to create a Client.

type ConfigUpdate

type ConfigUpdate struct {
	// Name is the sandbox name (required for sandbox-scoped updates).
	Name string
	// Policy is the typed security policy for a full policy replacement. Nil means no policy change.
	Policy *SandboxPolicy
	// SettingKey is a single setting key to mutate.
	SettingKey string
	// SettingValue is the setting value for upsert. Nil means no value change.
	SettingValue *SettingValue
	// DeleteSetting deletes the setting key when true.
	DeleteSetting bool
	// Global applies the update at gateway-global scope when true.
	Global bool
	// MergeOperations is a list of typed policy merge operations.
	MergeOperations []PolicyMergeOperation
	// ExpectedResourceVersion is for optimistic concurrency (0 = skip check).
	ExpectedResourceVersion uint64
	// Annotations is caller-provided metadata for sandbox-scoped updates.
	Annotations map[string]string
}

ConfigUpdate represents a configuration mutation request. For sandbox-scoped updates, set Name to the sandbox name. For global-scoped updates, set Global to true.

type ConfigUpdateResult

type ConfigUpdateResult struct {
	// Version is the assigned policy version.
	Version uint32
	// PolicyHash is the SHA-256 of the serialized policy.
	PolicyHash string
	// SettingsRevision is the settings revision for the modified scope.
	SettingsRevision uint64
	// Deleted is true when a setting delete removed an existing key.
	Deleted bool
	// Annotations contains sandbox metadata annotations after the update.
	Annotations map[string]string
}

ConfigUpdateResult holds the result of a configuration update operation. Named ConfigUpdateResult to avoid collision with profile.UpdateResult.

type ConfigurationAdmissionState

type ConfigurationAdmissionState string

ConfigurationAdmissionState describes validation of an effective configuration.

const (
	ConfigurationAdmissionUnknown  ConfigurationAdmissionState = "unknown"
	ConfigurationAdmissionPending  ConfigurationAdmissionState = "pending"
	ConfigurationAdmissionAccepted ConfigurationAdmissionState = "accepted"
	ConfigurationAdmissionRejected ConfigurationAdmissionState = "rejected"
)

Configuration admission states reported by the gateway.

type CreateOption

type CreateOption func(*createConfig)

CreateOption configures a Create call.

func WithAnnotations

func WithAnnotations(annotations map[string]string) CreateOption

WithAnnotations sets annotations on the created resource.

func WithLabels

func WithLabels(labels map[string]string) CreateOption

WithLabels sets labels on the created resource.

func WithServiceExposures

func WithServiceExposures(exposures ...ServiceExposure) CreateOption

WithServiceExposures registers loopback HTTP services with the created sandbox. Leave Service empty for the unnamed endpoint.

type CredentialHandle

type CredentialHandle struct {
	Driver   string
	Handle   string
	Metadata map[string]string
}

CredentialHandle is an opaque handle for a provider credential stored by gateway credential storage. Handles are created by OpenShell and are not accepted as user-authored input.

type CredentialTokenGrant

type CredentialTokenGrant struct {
	TokenEndpoint   string
	Audience        string
	JWTSVIDAudience string
	Scopes          []string
	// CacheTTL retains the exact protobuf duration, including presence and nanoseconds.
	CacheTTL            *ProfileDuration
	AudienceOverrides   []TokenGrantAudienceOverride
	ClientAssertionType string
	GrantType           CredentialTokenGrantType
	SubjectToken        *TokenGrantSubjectToken
	RequestedTokenType  string
}

CredentialTokenGrant configures dynamic credential acquisition via OAuth2 grant.

type CredentialTokenGrantType

type CredentialTokenGrantType string

CredentialTokenGrantType describes which OAuth2 grant type to use for dynamic credentials.

const (
	CredentialTokenGrantTypeClientCredentials CredentialTokenGrantType = "ClientCredentials"
	CredentialTokenGrantTypeTokenExchange     CredentialTokenGrantType = "TokenExchange"
)

CredentialTokenGrantType values.

type CurrentUser

type CurrentUser struct {
	Subject          string
	DisplayName      string
	Roles            []string
	Scopes           []string
	IdentityProvider string
}

CurrentUser holds the authenticated caller's identity.

type DeleteOptions

type DeleteOptions struct {
	AllowMissing bool
}

DeleteOptions configures the missing-target contract.

type DeletionOutcome

type DeletionOutcome int32

DeletionOutcome distinguishes completion from asynchronous acceptance. Unknown numeric values are preserved and must not be treated as completion.

const (
	DeletionUnspecified DeletionOutcome = iota
	DeletionCompleted
	DeletionAccepted
	DeletionAlreadyAbsent
)

Known deletion outcomes. Only Completed and AlreadyAbsent establish completion.

type DeletionResult

type DeletionResult struct {
	Outcome DeletionOutcome
	// SandboxID is empty for non-sandbox deletions and missing targets.
	SandboxID string
}

DeletionResult describes the original target, not a same-name replacement.

type DetachProviderResult

type DetachProviderResult struct {
	Sandbox  *Sandbox
	Detached bool
}

DetachProviderResult holds the result of detaching a provider from a sandbox.

type DraftChunkApproval

type DraftChunkApproval struct {
	ChunkID     string
	ReviewToken string
}

DraftChunkApproval binds one bulk approval decision to a reviewed chunk.

type DraftHistoryEntry

type DraftHistoryEntry struct {
	// Timestamp is when the event occurred.
	Timestamp time.Time
	// EventType is the event type (e.g., "approved", "rejected", "cleared").
	EventType string
	// Description is a human-readable description.
	Description string
	// ChunkID is the associated chunk ID (if applicable).
	ChunkID string
}

DraftHistoryEntry represents a single event in the draft policy history.

type DraftPolicy

type DraftPolicy struct {
	// Chunks contains the draft policy chunks.
	Chunks []PolicyChunk
	// RollingSummary is an LLM-generated summary of all analysis.
	RollingSummary string
	// DraftVersion is the current draft version number.
	DraftVersion uint64
	// LastAnalyzedAt is when the last analysis completed.
	LastAnalyzedAt time.Time
}

DraftPolicy contains the full draft policy state returned by GetDraft.

type EffectiveSetting

type EffectiveSetting struct {
	Value SettingValue
	Scope SettingScope
}

EffectiveSetting is a setting value paired with the scope it was resolved from.

type EndpointFailure

type EndpointFailure struct {
	// Domain names the subsystem whose closed code set explains the failure.
	Domain EndpointFailureDomain
	// Code is a stable lower_snake_case code from the domain's closed set,
	// such as provider_authorization_required.
	Code string
	// RecoveryAction is the action documented for Code.
	RecoveryAction RefreshRecoveryAction
	// Provider is the configured provider whose credential failed. It is empty
	// when the failure happened before a credential was selected.
	Provider string
	// CredentialKey is the configured credential name within Provider, never a
	// credential value. It is empty when Provider is empty.
	CredentialKey string
	// Stage is the step that observed the failure, from the domain's closed
	// set, such as gateway_rpc.
	Stage string
	// UpstreamHTTPStatus is the HTTP status a token service returned. Nil means
	// no status was received.
	UpstreamHTTPStatus *uint32
	// RequestID is the supervisor-minted UUID of the refused exchange. The
	// workload receives the same value in the x-openshell-request-id response
	// header.
	RequestID string
}

EndpointFailure explains why an observed exchange failed. It does not establish that the endpoint is unhealthy. No field carries remote text.

type EndpointFailureDomain

type EndpointFailureDomain string

EndpointFailureDomain names the subsystem that explains an endpoint failure.

const (
	// EndpointFailureDomainUnspecified means the domain was absent or was not recognized.
	EndpointFailureDomainUnspecified EndpointFailureDomain = "Unspecified"
	// EndpointFailureDomainTokenGrant means a dynamic token grant for a provider
	// credential failed, so OpenShell refused the request before any of it
	// reached the endpoint.
	EndpointFailureDomainTokenGrant EndpointFailureDomain = "TokenGrant"
)

EndpointFailureDomain values select the closed set that Code and Stage come from.

type EndpointResult

type EndpointResult string

EndpointResult classifies the last accepted network result for a tool endpoint.

const (
	// EndpointUnspecified means the result was absent or was not recognized.
	EndpointUnspecified EndpointResult = "Unspecified"
	// EndpointNoObservedExchange means the active configuration and supervisor
	// session have no applicable observation.
	EndpointNoObservedExchange EndpointResult = "NoObservedExchange"
	// EndpointHTTPResponseReceived means an HTTP status below 400 was received.
	// The response body can still contain a tool error.
	EndpointHTTPResponseReceived EndpointResult = "HttpResponseReceived"
	// EndpointPolicyDenied means OpenShell policy denied the request locally.
	EndpointPolicyDenied EndpointResult = "PolicyDenied"
	// EndpointCredentialUnavailable means a required managed credential was unavailable.
	EndpointCredentialUnavailable EndpointResult = "CredentialUnavailable"
	// EndpointTLSFailed means TLS setup for the upstream connection failed.
	EndpointTLSFailed EndpointResult = "TlsFailed"
	// EndpointTransportFailed means the transport failed before an HTTP response arrived.
	EndpointTransportFailed EndpointResult = "TransportFailed"
	// EndpointUpstreamRejected means the server returned an HTTP status of 400 or higher.
	EndpointUpstreamRejected EndpointResult = "UpstreamRejected"
)

EndpointResult values describe passive observations of actual traffic.

type EndpointStatus

type EndpointStatus struct {
	// EndpointID selects this endpoint without parsing its address or display text.
	EndpointID string
	Host       string
	Ports      []uint32
	Path       string
	LastResult EndpointResult
	// LastReportedAt is the RFC 3339 UTC rendering of the time when the gateway accepted the
	// observation, not the request time. Retained evidence can be accepted after
	// a reset. NoObservedExchange has no report timestamp.
	LastReportedAt string
	// LastFailure is the bounded cause of LastResult, when the supervisor
	// classified it. Each failure domain names the results it explains; token
	// grant failures accompany EndpointCredentialUnavailable. Each later
	// observation replaces or clears it, and the resets that clear LastResult
	// also clear it. Nil means no classified cause.
	LastFailure *EndpointFailure
}

EndpointStatus holds a configured tool endpoint and its last accepted network result. Observations aggregate configured callers across the listed ports; the result does not establish present availability or successful tool execution.

type ErrorCode

type ErrorCode int

ErrorCode classifies SDK errors by their gRPC origin.

const (
	ErrorNotFound ErrorCode = iota + 1
	ErrorAlreadyExists
	ErrorUnavailable
	ErrorPermissionDenied
	ErrorInvalidArgument
	ErrorDeadlineExceeded
	ErrorCancelled
	ErrorInternal
	ErrorUnimplemented
	ErrorConflict
	ErrorUnauthenticated
)

ErrorCode values for classifying gRPC errors.

func (ErrorCode) String

func (c ErrorCode) String() string

String returns the human-readable name of the error code.

type ErrorInfo

type ErrorInfo struct {
	Reason   string
	Domain   string
	Metadata map[string]string
}

ErrorInfo describes a server failure using a stable reason within a domain.

type Event

type Event[T any] struct {
	Type   EventType
	Object T
	Err    error
}

Event represents a watch event carrying a resource that changed.

type EventType

type EventType string

EventType classifies watch events.

const (
	EventAdded    EventType = "ADDED"
	EventModified EventType = "MODIFIED"
	EventDeleted  EventType = "DELETED"
	EventError    EventType = "ERROR"
)

EventType values for watch events.

type ExecChunk

type ExecChunk struct {
	Stream StreamType
	Data   []byte
}

ExecChunk represents a single chunk of output from a streaming command execution.

type ExecOptions

type ExecOptions struct {
	Env     map[string]string
	WorkDir string
	// NoLoginShell skips sourcing shell login/profile startup files before the
	// command. The zero value (false) preserves login-shell behavior. Set it
	// for automation and managed checks that need predictable startup behavior.
	NoLoginShell bool
}

ExecOptions configures command execution.

type ExecResult

type ExecResult struct {
	ExitCode int
	Stdout   []byte
	Stderr   []byte
}

ExecResult holds the collected output of a completed command execution.

type ExtensionInfo

type ExtensionInfo struct {
	Kind                  ExtensionKind
	ConfiguredName        string
	ImplementationName    string
	ImplementationVersion string
	ProtocolMajor         uint32
	ProtocolMinor         uint32
	SupportedCapabilities []string
	RequiredCapabilities  []string
}

ExtensionInfo describes one successful gateway/extension negotiation.

type ExtensionKind

type ExtensionKind string

ExtensionKind identifies one supported extension family.

const (
	ExtensionKindComputeDriver        ExtensionKind = "ComputeDriver"
	ExtensionKindCredentialDriver     ExtensionKind = "CredentialDriver"
	ExtensionKindGatewayInterceptor   ExtensionKind = "GatewayInterceptor"
	ExtensionKindSupervisorMiddleware ExtensionKind = "SupervisorMiddleware"
	ExtensionKindUnknown              ExtensionKind = "Unknown"
)

Extension kind constants.

type FieldViolation

type FieldViolation struct {
	Field       string
	Description string
}

FieldViolation identifies an invalid request field.

type FilesystemPolicy

type FilesystemPolicy struct {
	// IncludeWorkdir auto-includes the working directory as read-write.
	IncludeWorkdir bool
	// ReadOnly is the list of read-only directory paths.
	// Nil means no read-only directories; an empty slice is distinct from nil.
	ReadOnly []string
	// ReadWrite is the list of read-write directory paths.
	// Nil means no read-write directories; an empty slice is distinct from nil.
	ReadWrite []string
}

FilesystemPolicy controls which directories the sandbox can access in read-only or read-write mode.

type GatewayConfig

type GatewayConfig struct {
	// Settings is the global settings map.
	Settings map[string]SettingValue
	// SettingsRevision is a monotonically increasing revision for gateway-global settings.
	SettingsRevision uint64
}

GatewayConfig represents gateway-global settings.

type GatewayInfo

type GatewayInfo struct {
	Status         ServiceStatus
	Version        string
	ComputeDrivers []ComputeDriverInfo
	Extensions     []ExtensionInfo
}

GatewayInfo holds operational metadata about the gateway.

type GetDraftOption

type GetDraftOption func(*getDraftConfig)

GetDraftOption configures a GetDraft call.

func WithStatusFilter

func WithStatusFilter(status string) GetDraftOption

WithStatusFilter filters draft chunks by approval status.

type GetStatusOption

type GetStatusOption func(*getStatusConfig)

GetStatusOption configures a GetStatus call.

func WithStatusGlobal

func WithStatusGlobal(global bool) GetStatusOption

WithStatusGlobal enables global policy mode on GetStatus. When true, the query retrieves gateway-global policy status instead of sandbox-scoped status, and the sandbox name and workspace parameters are ignored.

func WithVersion

func WithVersion(version uint32) GetStatusOption

WithVersion queries a specific policy version instead of the latest.

type GraphqlOperation

type GraphqlOperation struct {
	OperationType string
	OperationName string
	Fields        []string
}

GraphqlOperation describes a GraphQL operation for persisted-query validation.

type HealthResult

type HealthResult struct {
	Healthy bool
	Version string
}

HealthResult holds the result of a health check.

type ImportResult

type ImportResult struct {
	Diagnostics []ProfileDiagnostic
	Profiles    []ProviderProfile
	Imported    bool
}

ImportResult holds the result of a profile import operation.

type L7Allow

type L7Allow struct {
	Method        string
	Path          string
	Command       string
	Query         map[string]L7QueryMatcher
	OperationType string
	OperationName string
	Fields        []string
	Params        map[string]L7QueryMatcher
}

L7Allow specifies layer-7 allow criteria for HTTP/GraphQL traffic.

type L7DenyRule

type L7DenyRule struct {
	Method        string
	Path          string
	Command       string
	Query         map[string]L7QueryMatcher
	OperationType string
	OperationName string
	Fields        []string
	Params        map[string]L7QueryMatcher
}

L7DenyRule specifies layer-7 deny criteria for HTTP/GraphQL traffic.

type L7QueryMatcher

type L7QueryMatcher struct {
	Glob string
	Any  []string
}

L7QueryMatcher matches query parameters by glob pattern or exact values.

type L7Rule

type L7Rule struct {
	// Allow holds the layer-7 allow criteria.
	Allow *L7Allow
}

L7Rule wraps an L7 allow rule.

type L7RuleTarget

type L7RuleTarget struct {
	// RuleName names the base-policy rule containing the endpoint.
	RuleName string
	// Host is the endpoint host, matched case-insensitively.
	Host string
	// Ports lists every port affected by the append, not only a lookup port.
	Ports []uint32
	// Path selects the endpoint path, distinct from an appended request path.
	// Nil requires a unique endpoint; a pointer to "" selects an unscoped endpoint.
	Path *string
	// Binaries lists every binary governed by the containing rule.
	// Exactly one of a nonempty Binaries list or AnyBinary=true is required.
	Binaries []PolicyNetworkBinary
	// AnyBinary explicitly acknowledges a rule with unrestricted binary scope.
	AnyBinary bool
}

L7RuleTarget identifies an endpoint and declares its complete affected scope. The gateway requires the ports and binary scope to match the stored endpoint and rule before appending any layer-7 rules.

type LandlockPolicy

type LandlockPolicy struct {
	// Compatibility is the compatibility mode (e.g., "best_effort", "hard_requirement").
	Compatibility string
}

LandlockPolicy configures the Linux Landlock LSM for filesystem restriction enforcement.

type LintResult

type LintResult struct {
	Diagnostics []ProfileDiagnostic
	Valid       bool
}

LintResult holds the result of a profile lint operation.

type ListOptions

type ListOptions struct {
	// PageSize is the maximum number of resources requested per RPC.
	PageSize int
	// PageToken resumes after a page returned by the same list query.
	PageToken     string
	LabelSelector string
	// AllWorkspaces selects a platform-admin view across workspace boundaries.
	AllWorkspaces bool
}

ListOptions configures resource listing with pagination and filtering.

type ListPolicyOption

type ListPolicyOption func(*listPolicyConfig)

ListPolicyOption configures a List call.

func WithListGlobal

func WithListGlobal(global bool) ListPolicyOption

WithListGlobal enables global policy mode on List. When true, the query retrieves gateway-global policy revisions instead of sandbox-scoped ones, and the workspace parameter is ignored.

func WithPageSize

func WithPageSize(pageSize int32) ListPolicyOption

WithPageSize sets the maximum revisions requested per page.

func WithPageToken

func WithPageToken(pageToken string) ListPolicyOption

WithPageToken resumes listing from an opaque token returned by a previous page.

type LogLine

type LogLine struct {
	// Timestamp is when the log entry was recorded.
	Timestamp time.Time
	// Level is the log severity level (e.g., "INFO", "WARN", "ERROR").
	Level string
	// Target is the log target/module.
	Target string
	// Message is the log message text.
	Message string
	// Source is the log source: "gateway" or "sandbox".
	Source string
	// Fields contains structured key-value fields from the tracing event.
	Fields map[string]string
}

LogLine represents a single log entry from a sandbox.

type LogOption

type LogOption func(*logConfig)

LogOption configures a GetLogs call.

func WithLogLines

func WithLogLines(n uint32) LogOption

WithLogLines sets the maximum number of log lines to return.

func WithLogMinLevel

func WithLogMinLevel(level string) LogOption

WithLogMinLevel sets the minimum log level to include.

func WithLogSince

func WithLogSince(t time.Time) LogOption

WithLogSince filters logs to entries at or after the given time.

func WithLogSources

func WithLogSources(sources ...string) LogOption

WithLogSources filters logs by source (e.g., "gateway", "sandbox").

type LogResult

type LogResult struct {
	// Lines contains the log entries in chronological order.
	Lines []LogLine
	// BufferTotal is the total number of lines in the server's buffer.
	BufferTotal uint32
}

LogResult contains the result of a GetLogs call.

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Error(err error, msg string, keysAndValues ...any)
}

Logger defines structured logging for the SDK. Compatible with logr.Logger and slog.Logger adapters.

type McpOptions

type McpOptions struct {
	StrictToolNames         *bool
	AllowAllKnownMcpMethods *bool
	// Versions lists the exact MCP protocol revisions accepted by the endpoint.
	// An empty list represents omission at the protobuf transport boundary; the
	// checked policy or server ingress materializes the pinned default
	// "2025-11-25" before storing canonical state. Nonempty lists remain exact
	// allowlists.
	Versions []string
}

McpOptions configures MCP-specific policy controls on a network endpoint.

type MiddlewareEndpointSelector

type MiddlewareEndpointSelector struct {
	Include []string
	Exclude []string
}

MiddlewareEndpointSelector controls which admitted destinations use a middleware config, using host glob patterns.

type NetworkAccessPreset

type NetworkAccessPreset int32

NetworkAccessPreset selects a predefined endpoint access policy.

const (
	// NetworkAccessPresetUnspecified selects no access preset.
	NetworkAccessPresetUnspecified NetworkAccessPreset = 0
	// NetworkAccessPresetReadOnly permits read operations.
	NetworkAccessPresetReadOnly NetworkAccessPreset = 1
	// NetworkAccessPresetReadWrite permits read and write operations.
	NetworkAccessPresetReadWrite NetworkAccessPreset = 2
	// NetworkAccessPresetFull permits every operation supported by the protocol.
	NetworkAccessPresetFull NetworkAccessPreset = 3
)

type NetworkBinary

type NetworkBinary struct {
	Path string
}

NetworkBinary describes a binary artifact provided by a profile.

type NetworkCredentialBinding

type NetworkCredentialBinding struct {
	Provider string
}

NetworkCredentialBinding binds an endpoint to static credentials from an attached provider.

type NetworkEndpoint

type NetworkEndpoint struct {
	Host     string
	Port     uint32
	Protocol string
}

NetworkEndpoint describes a network endpoint provided by a profile.

type NetworkEnforcementMode

type NetworkEnforcementMode int32

NetworkEnforcementMode controls whether an endpoint audits or enforces L7 rules.

const (
	// NetworkEnforcementModeUnspecified uses the documented audit default.
	NetworkEnforcementModeUnspecified NetworkEnforcementMode = 0
	// NetworkEnforcementModeEnforce blocks policy violations.
	NetworkEnforcementModeEnforce NetworkEnforcementMode = 1
	// NetworkEnforcementModeAudit logs policy violations without blocking them.
	NetworkEnforcementModeAudit NetworkEnforcementMode = 2
)

type NetworkMiddlewareConfig

type NetworkMiddlewareConfig struct {
	Name       string
	Middleware string
	Config     map[string]any
	OnError    string
	Endpoints  *MiddlewareEndpointSelector
	Order      int32
}

NetworkMiddlewareConfig configures a supervisor middleware pipeline for network egress. Middleware configs are referenced by name in the policy.

type NetworkPolicyRule

type NetworkPolicyRule struct {
	// Name is the map key for this rule in the sandbox policy.
	Name string
	// Endpoints lists the network endpoints governed by this rule.
	Endpoints []PolicyNetworkEndpoint
	// Binaries lists the binaries governed by this rule.
	Binaries []PolicyNetworkBinary
}

NetworkPolicyRule defines a named network policy rule containing endpoints and binaries.

type NetworkTLSMode

type NetworkTLSMode int32

NetworkTLSMode controls TLS handling for a policy endpoint.

const (
	// NetworkTLSModeUnspecified uses automatic TLS handling.
	NetworkTLSModeUnspecified NetworkTLSMode = 0
	// NetworkTLSModeSkip disables TLS inspection.
	NetworkTLSModeSkip NetworkTLSMode = 1
	// NetworkTLSModeTerminate is rejected by policy validation.
	NetworkTLSModeTerminate NetworkTLSMode = 2
	// NetworkTLSModePassthrough is rejected by policy validation.
	NetworkTLSModePassthrough NetworkTLSMode = 3
)

type PolicyChunk

type PolicyChunk struct {
	// ID is the unique chunk identifier.
	ID string
	// Status is the approval status: "pending", "approved", "rejected".
	Status string
	// RuleName is the proposed network_policies map key.
	RuleName string
	// ProposedRule is the proposed network policy rule.
	ProposedRule *NetworkPolicyRule

	// Rationale is a human-readable explanation of why this rule is proposed.
	Rationale string
	// SecurityNotes contains security concerns flagged by analysis (empty if none).
	SecurityNotes string
	// Confidence is the analysis confidence score (0.0-1.0).
	Confidence float32
	// DenialSummaryIDs lists the IDs of denial summaries that led to this chunk.
	DenialSummaryIDs []string
	// CreatedAt is when the chunk was created.
	CreatedAt time.Time
	// DecidedAt is when the user approved/rejected (zero if undecided).
	DecidedAt time.Time
	// Stage is the recommendation stage: "initial" or "refined".
	Stage string
	// SupersedesChunkID is the initial chunk ID this refined chunk replaces.
	SupersedesChunkID string
	// HitCount is how many times this endpoint was seen across denial flush cycles.
	HitCount int32
	// FirstSeen is the first time this endpoint was proposed.
	FirstSeen time.Time
	// LastSeen is the most recent time this endpoint was re-proposed.
	LastSeen time.Time
	// Binary is the binary path that triggered the denial.
	Binary string
	// ValidationResult is the prover output from gateway-side static checks.
	ValidationResult string
	// RejectionReason is the operator-supplied text accompanying a rejection.
	RejectionReason string
	// ApplicationError is the complete-candidate preflight/application failure.
	ApplicationError string
	// ReviewToken binds an approval to the exact evaluated candidate.
	ReviewToken                  string
	CurrentEffectivePolicyHash   string
	CandidateEffectivePolicyHash string
	CurrentEffectivePolicy       *SandboxPolicy
	CandidateEffectivePolicy     *SandboxPolicy
}

PolicyChunk represents a single proposed policy change in the draft inbox.

type PolicyLoadStatus

type PolicyLoadStatus int

PolicyLoadStatus represents the load state of a policy revision.

const (
	// PolicyLoadStatusUnspecified is the default zero value.
	PolicyLoadStatusUnspecified PolicyLoadStatus = iota
	// PolicyLoadStatusPending means the policy is queued for loading.
	PolicyLoadStatusPending
	// PolicyLoadStatusLoaded means the policy was successfully loaded.
	PolicyLoadStatusLoaded
	// PolicyLoadStatusFailed means the policy failed to load.
	PolicyLoadStatusFailed
	// PolicyLoadStatusSuperseded means a newer revision replaced this one.
	PolicyLoadStatusSuperseded
)

func (PolicyLoadStatus) String

func (s PolicyLoadStatus) String() string

String returns the human-readable name of the load status.

type PolicyMergeOperation

type PolicyMergeOperation struct {
	// AddRule adds a new named network policy rule.
	AddRule *AddNetworkRule
	// RemoveEndpoint removes a single endpoint from a rule.
	RemoveEndpoint *RemoveNetworkEndpoint
	// RemoveRule removes an entire named rule.
	RemoveRule *RemoveNetworkRule
	// AddDenyRules appends deny rules to an endpoint.
	AddDenyRules *AddDenyRules
	// AddAllowRules appends allow rules to an endpoint.
	AddAllowRules *AddAllowRules
	// RemoveBinary removes a binary from a rule.
	RemoveBinary *RemoveNetworkBinary
}

PolicyMergeOperation represents a single atomic policy mutation. Exactly one of the pointer fields must be non-nil, modelling the proto oneof.

type PolicyNetworkBinary

type PolicyNetworkBinary struct {
	// Path is the filesystem path to the binary.
	Path string
}

PolicyNetworkBinary identifies a binary subject to network policy enforcement. This is distinct from NetworkBinary which is the simplified profile-level binary.

type PolicyNetworkEndpoint

type PolicyNetworkEndpoint struct {
	Host                         string
	Port                         uint32
	Ports                        []uint32
	Protocol                     string
	TLS                          NetworkTLSMode
	Enforcement                  NetworkEnforcementMode
	Access                       NetworkAccessPreset
	Rules                        []L7Rule
	AllowedIPs                   []string
	DenyRules                    []L7DenyRule
	AllowEncodedSlash            bool
	PersistedQueries             string
	GraphqlPersistedQueries      map[string]GraphqlOperation
	GraphqlMaxBodyBytes          uint32
	Path                         string
	WebsocketCredentialRewrite   bool
	RequestBodyCredentialRewrite bool
	// AllowUninspectedCredentials explicitly permits credential-bearing traffic
	// on paths OpenShell cannot inspect or rewrite.
	AllowUninspectedCredentials bool
	// ProviderCredentialed is gateway-derived provenance indicating that the
	// endpoint belongs to an attached credentialed provider.
	ProviderCredentialed bool
	AdvisorProposed      bool
	CredentialSigning    string
	SigningService       string
	SigningRegion        string
	JSONRPCMaxBodyBytes  uint32
	Mcp                  *McpOptions
	CredentialBinding    *NetworkCredentialBinding
}

PolicyNetworkEndpoint describes a full network endpoint with its access controls as used in sandbox network policy rules. This is distinct from NetworkEndpoint which is the simplified profile-level endpoint (Host, Port, Protocol only).

type PolicySource

type PolicySource string

PolicySource indicates the source of the policy payload in a SandboxConfig response.

const (
	PolicySourceUnspecified PolicySource = ""
	PolicySourceSandbox     PolicySource = "sandbox"
	PolicySourceGlobal      PolicySource = "global"
)

PolicySource constants.

type PolicyStatusResult

type PolicyStatusResult struct {
	// Revision is the queried policy revision.
	Revision SandboxPolicyRevision
	// ActiveVersion is the currently active (loaded) policy version.
	ActiveVersion uint32
}

PolicyStatusResult contains the status of a sandbox's policy.

type ProcessPolicy

type ProcessPolicy struct {
	// RunAsUser is the user name for sandboxed processes.
	RunAsUser string
	// RunAsGroup is the group name for sandboxed processes.
	RunAsGroup string
}

ProcessPolicy controls the user and group identity under which sandboxed processes execute.

type ProfileCategory

type ProfileCategory string

ProfileCategory classifies a provider profile.

const (
	ProfileCategoryOther         ProfileCategory = "Other"
	ProfileCategoryInference     ProfileCategory = "Inference"
	ProfileCategoryAgent         ProfileCategory = "Agent"
	ProfileCategorySourceControl ProfileCategory = "SourceControl"
	ProfileCategoryMessaging     ProfileCategory = "Messaging"
	ProfileCategoryData          ProfileCategory = "Data"
	ProfileCategoryKnowledge     ProfileCategory = "Knowledge"
)

ProfileCategory values.

type ProfileCredential

type ProfileCredential struct {
	Name        string
	Description string
	EnvVars     []string
	Required    bool
	// StablePlaceholder uses an opaque identity-bound resolver handle across
	// value-only external provider updates. It does not change secret
	// classification or bypass endpoint authorization.
	StablePlaceholder bool
	Secret            bool
	Refresh           *ProfileCredentialRefresh
	AuthStyle         string
	HeaderName        string
	QueryParam        string
	PathTemplate      string
	TokenGrant        *CredentialTokenGrant
}

ProfileCredential defines a single credential required by a provider profile.

type ProfileCredentialRefresh

type ProfileCredentialRefresh struct {
	Strategy RefreshStrategy
	TokenURL string
	Scopes   []string
	// RefreshBefore retains the exact protobuf duration, including presence and nanoseconds.
	RefreshBefore *ProfileDuration
	// MaxLifetime retains the exact protobuf duration, including presence and nanoseconds.
	MaxLifetime       *ProfileDuration
	Material          []ProfileCredentialRefreshMaterial
	AdditionalOutputs []ProfileCredentialRefreshOutput
}

ProfileCredentialRefresh declares how a profile credential is refreshed.

type ProfileCredentialRefreshMaterial

type ProfileCredentialRefreshMaterial struct {
	Name        string
	Description string
	Required    bool
	Secret      bool
}

ProfileCredentialRefreshMaterial declares one input required by a refresh strategy.

type ProfileCredentialRefreshOutput

type ProfileCredentialRefreshOutput struct {
	Output     string
	Credential string
}

ProfileCredentialRefreshOutput maps a minted output to another credential.

type ProfileDiagnostic

type ProfileDiagnostic struct {
	Source    string
	ProfileID string
	Field     string
	Message   string
	Severity  string
}

ProfileDiagnostic is a validation finding from Import, Update, or Lint.

type ProfileDiscovery

type ProfileDiscovery struct {
	Credentials []string
}

ProfileDiscovery holds local discovery configuration for a profile.

type ProfileDuration

type ProfileDuration struct {
	Seconds int64
	Nanos   int32
}

ProfileDuration represents a protobuf duration without importing generated protobuf packages into the curated SDK types. A nil pointer means absent; a non-nil zero value means an explicitly present zero duration.

type ProfileFile

type ProfileFile struct {
	Path    string
	Content string
	EnvVar  string
}

ProfileFile declares non-secret content served at a virtual sandbox path. EXPERIMENTAL: This API and its behavior may change or be removed.

type ProfileImportItem

type ProfileImportItem struct {
	Profile ProviderProfile
	Source  string
}

ProfileImportItem is an item submitted for profile import or lint validation.

type Provider

type Provider struct {
	ID                string
	Name              string
	Type              string
	CreatedAt         time.Time
	Labels            map[string]string
	Annotations       map[string]string
	ResourceVersion   uint64
	Workspace         string
	DeletionTimestamp *time.Time
	Spec              ProviderSpec
}

Provider represents an AI provider registration.

type ProviderProfile

type ProviderProfile struct {
	ID          string
	DisplayName string
	Description string
	Category    ProfileCategory
	Credentials []ProfileCredential
	// Files is EXPERIMENTAL. This API and its behavior may change or be removed.
	Files            []ProfileFile
	Endpoints        []NetworkEndpoint
	Binaries         []NetworkBinary
	InferenceCapable bool
	Discovery        ProfileDiscovery
	ResourceVersion  uint64
	Annotations      map[string]string
	Source           string
	Scope            string
}

ProviderProfile defines a provider type template with credentials schema, files, endpoints, binaries, and discovery configuration.

type ProviderSpec

type ProviderSpec struct {
	Credentials         map[string]string
	Config              map[string]string
	CredentialExpiresAt map[string]time.Time
	ProfileWorkspace    string
	CredentialHandles   map[string]CredentialHandle
}

ProviderSpec holds provider-specific configuration and credentials.

type RefreshConfig

type RefreshConfig struct {
	Provider           string
	CredentialKey      string
	Strategy           RefreshStrategy
	Material           map[string]string
	SecretMaterialKeys []string
	ExpiresAt          *time.Time
}

RefreshConfig holds configuration parameters for gateway-owned credential refresh on a provider credential.

type RefreshRecoveryAction

type RefreshRecoveryAction int

RefreshRecoveryAction describes the action required after a refresh failure.

const (
	// RefreshRecoveryActionUnspecified means no recovery action is required.
	RefreshRecoveryActionUnspecified RefreshRecoveryAction = iota
	// RefreshRecoveryActionRetry means OpenShell will retry automatically.
	RefreshRecoveryActionRetry
	// RefreshRecoveryActionReauthorize means the user must replace the OAuth grant.
	RefreshRecoveryActionReauthorize
	// RefreshRecoveryActionFixConfiguration means an operator must repair configuration.
	RefreshRecoveryActionFixConfiguration
	// RefreshRecoveryActionInvestigate means the failure is not recognized.
	RefreshRecoveryActionInvestigate
)

func (RefreshRecoveryAction) String

func (a RefreshRecoveryAction) String() string

String returns the provider-neutral recovery action name.

type RefreshStatus

type RefreshStatus struct {
	Provider      string
	ProviderID    string
	CredentialKey string
	Strategy      RefreshStrategy
	Status        string
	ExpiresAt     time.Time
	// NextRefreshAt is zero when no automatic refresh is scheduled. Use
	// RecoveryAction to distinguish a parked refresh from an unset timestamp.
	NextRefreshAt        time.Time
	LastRefreshAt        time.Time
	LastError            string
	RecoveryAction       RefreshRecoveryAction
	FailureCode          string
	ProviderErrorSubtype string
	LastErrorAt          time.Time
}

RefreshStatus reports the current state of credential refresh for a specific provider credential.

type RefreshStrategy

type RefreshStrategy string

RefreshStrategy describes how credentials are refreshed.

const (
	RefreshStrategyStatic                  RefreshStrategy = "Static"
	RefreshStrategyExternal                RefreshStrategy = "External"
	RefreshStrategyOAuth2RefreshToken      RefreshStrategy = "OAuth2RefreshToken"
	RefreshStrategyOAuth2ClientCredentials RefreshStrategy = "OAuth2ClientCredentials"
	RefreshStrategyGoogleServiceAccountJWT RefreshStrategy = "GoogleServiceAccountJWT"
	RefreshStrategyAWSStsAssumeRole        RefreshStrategy = "AWSStsAssumeRole"
)

RefreshStrategy values.

type RemoveNetworkBinary

type RemoveNetworkBinary struct {
	// RuleName is the name of the rule containing the binary.
	RuleName string
	// BinaryPath is the filesystem path of the binary to remove.
	BinaryPath string
}

RemoveNetworkBinary removes a binary from a named rule.

type RemoveNetworkEndpoint

type RemoveNetworkEndpoint struct {
	// RuleName is the name of the rule containing the endpoint.
	RuleName string
	// Host is the endpoint host to remove.
	Host string
	// Port is the endpoint port to remove.
	Port uint32
}

RemoveNetworkEndpoint removes a specific endpoint from a named rule.

type RemoveNetworkRule

type RemoveNetworkRule struct {
	// RuleName is the name of the rule to remove.
	RuleName string
}

RemoveNetworkRule removes an entire named rule from the policy.

type ResumeOptions

type ResumeOptions struct {
	// RestartIfRestoreFails lets the isolation backend boot the workload
	// cleanly when it cannot restore the retained memory state. When false,
	// resume fails instead.
	RestartIfRestoreFails bool
}

ResumeOptions configures how a suspended sandbox resumes.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries  int
	InitialWait time.Duration
	MaxWait     time.Duration
}

RetryPolicy configures automatic retry behavior for failed RPCs.

type SSHSession

type SSHSession struct {
	// SandboxID is the sandbox this session connects to.
	SandboxID string
	// Token is the session token for gateway tunnel authentication.
	// This is a sensitive credential — treat it like an API key.
	Token string
	// GatewayHost is the host for SSH proxy connection.
	GatewayHost string
	// GatewayPort is the gateway port (1-65535).
	GatewayPort uint32
	// GatewayScheme is the gateway protocol scheme ("http" or "https").
	GatewayScheme string
	// HostKeyFingerprint is the optional host key fingerprint.
	HostKeyFingerprint string
	// ExpiresAtMs is the session expiry in milliseconds since epoch.
	// Zero means no expiry.
	ExpiresAtMs int64
}

SSHSession represents an SSH session created for a sandbox. The Token field is sensitive and MUST NOT be logged or included in error messages. The String() method redacts the token to prevent accidental exposure via fmt or logging.

func (SSHSession) String

func (s SSHSession) String() string

String returns a human-readable representation with the Token redacted.

type Sandbox

type Sandbox struct {
	// HostKeyFingerprint is the stable SSH identity; empty on older runtimes.
	HostKeyFingerprint          string
	ID                          string
	Name                        string
	CreatedAt                   time.Time
	Labels                      map[string]string
	Annotations                 map[string]string
	ResourceVersion             uint64
	Workspace                   string
	DeletionTimestamp           *time.Time
	CreatedFromWorkloadTemplate *SandboxWorkloadTemplateProvenance
	Spec                        SandboxSpec
	Status                      SandboxStatus
	// ServiceURLs is populated by create operations and keyed by service name.
	// The empty key identifies the unnamed service.
	ServiceURLs map[string]string
}

Sandbox represents a sandbox instance.

type SandboxCondition

type SandboxCondition struct {
	Type               string
	Status             string
	Reason             string
	Message            string
	LastTransitionTime string
}

SandboxCondition describes an observed condition of a sandbox.

type SandboxConfig

type SandboxConfig struct {
	// Policy is the typed security policy for this sandbox. Nil means no policy in the response.
	Policy *SandboxPolicy
	// PolicyVersion is monotonically increasing per sandbox.
	PolicyVersion uint32
	// PolicyHash is the SHA-256 of the serialized policy payload.
	PolicyHash string
	// Settings is the effective settings resolved for this sandbox.
	Settings map[string]EffectiveSetting
	// ConfigRevision is the fingerprint for effective config (policy + settings).
	ConfigRevision uint64
	// PolicySource indicates where the policy came from (sandbox or global).
	PolicySource PolicySource
	// GlobalPolicyVersion is the global policy version (0 if not applicable).
	GlobalPolicyVersion uint32
	// ProviderEnvRevision is the fingerprint for provider credential inputs.
	ProviderEnvRevision uint64
	// PolicyValidationFailureMode is the gateway-configured posture for rejected
	// policy generations ("fail_closed" or "retain_last_valid").
	PolicyValidationFailureMode string
}

SandboxConfig represents the full configuration state of a sandbox, including policy, effective settings, and revision metadata.

type SandboxConfigurationAdmission

type SandboxConfigurationAdmission struct {
	State               ConfigurationAdmissionState
	PolicyVersion       uint32
	PolicyHash          string
	ConfigRevision      uint64
	ProviderEnvRevision uint64
	Error               string
}

SandboxConfigurationAdmission identifies a validated or rejected configuration. Supervisor instance fencing remains available through the raw protobuf API.

type SandboxGPURequirements

type SandboxGPURequirements struct {
	Count *uint32
}

SandboxGPURequirements defines template GPU requirements.

type SandboxPhase

type SandboxPhase string

SandboxPhase represents the lifecycle phase of a sandbox.

const (
	SandboxProvisioning SandboxPhase = "Provisioning"
	SandboxReady        SandboxPhase = "Ready"
	SandboxError        SandboxPhase = "Error"
	SandboxDeleting     SandboxPhase = "Deleting"
	SandboxUnknown      SandboxPhase = "Unknown"
	SandboxStopping     SandboxPhase = "Stopping"
	SandboxStopped      SandboxPhase = "Stopped"
	SandboxStarting     SandboxPhase = "Starting"
	SandboxCompleted    SandboxPhase = "Completed"
	SandboxSuspending   SandboxPhase = "Suspending"
	SandboxSuspended    SandboxPhase = "Suspended"
)

SandboxPhase values for sandbox lifecycle.

type SandboxPolicy

type SandboxPolicy struct {
	// Version is the policy version number. The server may override this on write.
	Version uint32
	// Filesystem controls which directories the sandbox can access.
	// Nil means no filesystem policy is specified.
	Filesystem *FilesystemPolicy
	// Landlock configures the Linux Landlock LSM.
	// Nil means no landlock policy is specified.
	Landlock *LandlockPolicy
	// Process controls the user and group identity for sandboxed processes.
	// Nil means no process policy is specified.
	Process *ProcessPolicy
	// NetworkPolicies contains named network access rules.
	// Nil means no network policies are specified; an empty map is distinct from nil.
	NetworkPolicies map[string]NetworkPolicyRule
	// NetworkMiddlewares contains named middleware pipeline configurations for
	// network egress. Nil means no middleware is specified; an empty map is distinct from nil.
	NetworkMiddlewares map[string]NetworkMiddlewareConfig
}

SandboxPolicy is the top-level security policy configuration for a sandbox. It contains filesystem access rules, Landlock LSM configuration, process identity rules, and named network access policies.

type SandboxPolicyRevision

type SandboxPolicyRevision struct {
	// Version is the policy version (monotonically increasing per sandbox).
	Version uint32
	// PolicyHash is the SHA-256 hash of the serialized policy payload.
	PolicyHash string
	// Status is the load status of this revision.
	Status PolicyLoadStatus
	// LoadError is the error message if status is Failed.
	LoadError string
	// CreatedAt is when this revision was created.
	CreatedAt time.Time
	// LoadedAt is when this revision was loaded by the sandbox.
	LoadedAt time.Time
	// Policy is the typed security policy for this revision. Nil when not requested or absent.
	Policy *SandboxPolicy
	// Provenance is immutable metadata supplied with this policy revision.
	Provenance map[string]string
}

SandboxPolicyRevision represents a versioned policy revision for a sandbox.

type SandboxResources

type SandboxResources struct {
	CPU    string
	Memory string
	// GPU requests GPU resources for template-backed sandboxes. A non-nil GPU
	// with nil Count requests the active driver's default GPU assignment.
	GPU *SandboxGPURequirements
}

SandboxResources defines portable sandbox resource requirements.

type SandboxRestartPolicy

type SandboxRestartPolicy string

SandboxRestartPolicy controls replacement after the canonical main process exits.

const (
	SandboxRestartNever     SandboxRestartPolicy = "Never"
	SandboxRestartOnFailure SandboxRestartPolicy = "OnFailure"
	SandboxRestartAlways    SandboxRestartPolicy = "Always"
)

Sandbox restart policy values.

type SandboxServiceLevel

type SandboxServiceLevel struct {
	Startup *SandboxStartup
}

SandboxServiceLevel describes desired operational characteristics.

type SandboxSpec

type SandboxSpec struct {
	LogLevel    string
	Environment map[string]string
	Template    *SandboxTemplate
	Providers   []string
	// GPU requests GPU resources using the active driver's default GPU assignment
	// when GPUCount is nil. GPUCount implies GPU for backward compatibility.
	GPU      bool
	GPUCount *uint32
	// Policy is the security policy for the sandbox. Nil means no policy specified.
	Policy        *SandboxPolicy
	Command       []string
	TTY           bool
	RestartPolicy SandboxRestartPolicy
}

SandboxSpec holds the desired state of a sandbox.

type SandboxStartup

type SandboxStartup struct {
	ReadyWithin time.Duration
	MaxBurst    uint32
}

SandboxStartup describes desired startup characteristics.

type SandboxStatus

type SandboxStatus struct {
	AgentPod             string
	AgentFd              string
	SandboxFd            string
	Phase                SandboxPhase
	Conditions           []SandboxCondition
	CurrentPolicyVersion uint32
	ExitCode             *int32
	// EndpointStatuses describes configured external tool endpoints and their
	// last accepted network results, independently of sandbox readiness.
	EndpointStatuses []EndpointStatus
	// LastTokenGrantFailure is the latest classified grant refusal for any
	// destination, including requests outside the MCP endpoint inventory.
	// A successful grant for the same destination and provider/credential clears
	// it. Before credential selection, any successful grant to that destination
	// clears it. Policy, provider, and session resets also clear it.
	// Nil means no retained cause.
	LastTokenGrantFailure  *TokenGrantFailureObservation
	ConfigurationAdmission *SandboxConfigurationAdmission
	RestartCount           uint32
	NextRestartAtMs        int64
	MainProcessStartedAtMs int64
}

SandboxStatus holds the observed state of a sandbox.

type SandboxTemplate

type SandboxTemplate struct {
	Image            string
	RuntimeClassName string
	AgentSocket      string
	Labels           map[string]string
	Annotations      map[string]string
	Environment      map[string]string
	UserNamespaces   *bool
	Resources        map[string]any
	DriverConfig     map[string]any
}

SandboxTemplate defines the container template for a sandbox.

type SandboxWorkloadConfig

type SandboxWorkloadConfig struct {
	Image       string
	Environment map[string]string
	Resources   *SandboxResources
}

SandboxWorkloadConfig defines the portable workload for a reusable template.

type SandboxWorkloadTemplate

type SandboxWorkloadTemplate struct {
	ID                string
	Name              string
	CreatedAt         time.Time
	Labels            map[string]string
	Annotations       map[string]string
	ResourceVersion   uint64
	Workspace         string
	DeletionTimestamp *time.Time
	Spec              SandboxWorkloadTemplateSpec
}

SandboxWorkloadTemplate is a reusable workspace-scoped sandbox template resource.

type SandboxWorkloadTemplateProvenance

type SandboxWorkloadTemplateProvenance struct {
	Name            string
	ResourceVersion string
}

SandboxWorkloadTemplateProvenance identifies the reusable template revision used to create a sandbox.

type SandboxWorkloadTemplateSpec

type SandboxWorkloadTemplateSpec struct {
	Workload            *SandboxWorkloadConfig
	DriverConfig        map[string]any
	DesiredServiceLevel *SandboxServiceLevel
}

SandboxWorkloadTemplateSpec holds reusable sandbox template settings.

type ServiceAuthorizationMode

type ServiceAuthorizationMode int32

ServiceAuthorizationMode controls handling of an incoming application Authorization header.

const (
	// ServiceAuthorizationModeStrip removes Authorization before proxying to the sandbox service.
	ServiceAuthorizationModeStrip ServiceAuthorizationMode = 1
	// ServiceAuthorizationModeBearerPassthrough forwards one valid bearer credential unchanged.
	ServiceAuthorizationModeBearerPassthrough ServiceAuthorizationMode = 2
)

type ServiceEndpoint

type ServiceEndpoint struct {
	ID                string
	SandboxID         string
	Sandbox           string
	Name              string
	TargetPort        uint32
	Domain            bool
	URL               string
	Workspace         string
	AuthorizationMode ServiceAuthorizationMode
}

ServiceEndpoint represents an exposed HTTP service on a sandbox.

type ServiceExposure

type ServiceExposure struct {
	Service           string
	TargetPort        uint32
	AuthorizationMode ServiceAuthorizationMode
}

ServiceExposure describes a loopback HTTP service to expose during sandbox creation.

type ServiceStatus

type ServiceStatus string

ServiceStatus describes the health state of the gateway.

const (
	ServiceStatusHealthy   ServiceStatus = "Healthy"
	ServiceStatusDegraded  ServiceStatus = "Degraded"
	ServiceStatusUnhealthy ServiceStatus = "Unhealthy"
	ServiceStatusUnknown   ServiceStatus = "Unknown"
)

ServiceStatus constants.

type SettingScope

type SettingScope string

SettingScope indicates whether a setting is controlled at sandbox or global level.

const (
	SettingScopeUnspecified SettingScope = ""
	SettingScopeSandbox     SettingScope = "sandbox"
	SettingScopeGlobal      SettingScope = "global"
)

SettingScope constants.

type SettingValue

type SettingValue struct {
	Type      SettingValueType
	StringVal string
	BoolVal   bool
	IntVal    int64
	BytesVal  []byte
}

SettingValue is a typed setting value supporting string, bool, int64, and bytes variants. The Type field indicates which value field is populated.

type SettingValueType

type SettingValueType string

SettingValueType identifies which typed field of a SettingValue is active.

const (
	SettingValueString SettingValueType = "string"
	SettingValueBool   SettingValueType = "bool"
	SettingValueInt    SettingValueType = "int"
	SettingValueBytes  SettingValueType = "bytes"
)

SettingValueType constants.

type StatusError

type StatusError struct {
	Code    ErrorCode
	Message string
	Cause   error
	// GRPCCode retains the exact transport code before SDK classification.
	GRPCCode int32
	// FieldViolations identifies invalid request fields without parsing Message.
	FieldViolations []FieldViolation
	// ErrorInfo is the server's machine-readable reason, domain, and metadata.
	ErrorInfo *ErrorInfo
	// RetryDelay is a suggested minimum delay, not proof a mutation is safe to repeat.
	RetryDelay *time.Duration
}

StatusError is the typed error returned by all SDK operations.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

type StreamType

type StreamType string

StreamType identifies which output stream a chunk belongs to.

const (
	StreamStdout StreamType = "stdout"
	StreamStderr StreamType = "stderr"
)

StreamType values for exec output.

type TLSConfig

type TLSConfig struct {
	CertFile string
	KeyFile  string
	CAFile   string
	Insecure bool
}

TLSConfig holds TLS connection settings.

type TokenGrantAudienceOverride

type TokenGrantAudienceOverride struct {
	Host     string
	Port     uint32
	Path     string
	Audience string
	Scopes   []string
}

TokenGrantAudienceOverride selects an endpoint-specific resource audience.

type TokenGrantFailureObservation

type TokenGrantFailureObservation struct {
	DestinationHost string
	DestinationPort uint32
	Failure         *EndpointFailure
}

TokenGrantFailureObservation records a refused grant's destination and cause. It describes the attempted call, not the remote server's current health.

type TokenGrantSubjectToken

type TokenGrantSubjectToken struct {
	Source           string
	Credential       string
	SubjectTokenType string
}

TokenGrantSubjectToken configures the subject token for token exchange grants.

type UndoResult

type UndoResult struct {
	// PolicyVersion is the new policy version after removal.
	PolicyVersion uint32
	// PolicyHash is the SHA-256 hash of the updated policy.
	PolicyHash string
}

UndoResult contains the result of undoing a draft chunk approval.

type UpdateResult

type UpdateResult struct {
	Diagnostics []ProfileDiagnostic
	Profile     *ProviderProfile
	Updated     bool
}

UpdateResult holds the result of a profile update operation.

type WaitOptions

type WaitOptions struct {
	PollInterval time.Duration
}

WaitOptions configures wait behavior. Use context for timeout control.

type WatchInterface

type WatchInterface[T any] interface {
	ResultChan() <-chan Event[T]
	Stop()
}

WatchInterface delivers a stream of typed events. Modeled after k8s.io/apimachinery/pkg/watch.Interface.

type WatchOptions

type WatchOptions struct {
	// StopOnTerminal causes the watch to close automatically when the sandbox
	// reaches a terminal phase (Ready or Error).
	StopOnTerminal bool
}

WatchOptions configures watch behavior.

type Workspace

type Workspace struct {
	ID                string
	Name              string
	CreatedAt         time.Time
	Labels            map[string]string
	Annotations       map[string]string
	ResourceVersion   uint64
	Workspace         string
	DeletionTimestamp *time.Time
	Phase             WorkspacePhase
}

Workspace represents a logical grouping of resources.

type WorkspaceMember

type WorkspaceMember struct {
	ID               string
	Name             string
	CreatedAt        time.Time
	Labels           map[string]string
	Annotations      map[string]string
	ResourceVersion  uint64
	PrincipalSubject string
	Role             WorkspaceRole
}

WorkspaceMember represents a user's membership in a workspace.

type WorkspacePhase

type WorkspacePhase string

WorkspacePhase describes the lifecycle state of a workspace.

const (
	WorkspaceActive      WorkspacePhase = "Active"
	WorkspaceTerminating WorkspacePhase = "Terminating"
	WorkspaceUnknown     WorkspacePhase = "Unknown"
)

WorkspacePhase constants.

type WorkspaceRole

type WorkspaceRole string

WorkspaceRole describes a member's role within a workspace.

const (
	WorkspaceRoleAdmin   WorkspaceRole = "Admin"
	WorkspaceRoleUser    WorkspaceRole = "User"
	WorkspaceRoleUnknown WorkspaceRole = "Unknown"
)

WorkspaceRole constants.

Jump to

Keyboard shortcuts

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