Documentation
¶
Overview ¶
Package v1 provides a Go SDK for interacting with OpenShell servers.
The SDK follows the Kubernetes client-go sub-client pattern: a single Client provides typed accessors for each resource domain (Sandboxes, Providers, Exec, Files, Health, Services, SSH, TCP, Config, Policy, Workspaces, Inference). All operations accept a context.Context and return idiomatic Go types. Proto-generated types never appear in the public API.
Quick Start ¶
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken("my-token"),
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
Sandbox Lifecycle ¶
sandbox, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{
Template: &v1.SandboxTemplate{Image: "python:3.12"},
Environment: map[string]string{"LANG": "en_US.UTF-8"},
}, nil)
if err != nil {
log.Fatal(err)
}
sandbox, err = client.Sandboxes().WaitReady(ctx, "default", sandbox.Name)
if err != nil {
log.Fatal(err)
}
Command Execution ¶
result, err := client.Exec().Run(ctx, "default", sandbox.Name, []string{"echo", "hello"}, v1.ExecOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Println(string(result.Stdout)) // "hello\n"
Error Handling ¶
_, err = client.Sandboxes().Get(ctx, "default", "missing")
if v1.IsNotFound(err) {
// handle not found
}
Watching ¶
watcher, err := client.Sandboxes().Watch(ctx, "default", sandbox.Name)
if err != nil {
log.Fatal(err)
}
defer watcher.Stop()
for event := range watcher.ResultChan() {
fmt.Printf("%s: %s\n", event.Type, event.Object.Name)
}
Watching with StopOnTerminal ¶
Use StopOnTerminal to auto-close the watcher when the sandbox reaches a terminal phase (Ready or Error):
watcher, err := client.Sandboxes().Watch(ctx, "default", sandbox.Name,
v1.WatchOptions{StopOnTerminal: true},
)
if err != nil {
log.Fatal(err)
}
for event := range watcher.ResultChan() {
fmt.Printf("phase: %s\n", event.Object.Status.Phase)
}
// channel closes automatically after Ready or Error
Service Exposure ¶
Expose an HTTP service running inside a sandbox and retrieve its public URL:
endpoint, err := client.Services().Expose(ctx, "default", "my-sandbox", "api", 8080, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Service URL: %s\n", endpoint.URL)
endpoints, err := client.Services().List(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
for _, ep := range endpoints {
fmt.Printf(" %s → port %d (URL: %s)\n", ep.ServiceName, ep.TargetPort, ep.URL)
}
Provider Profiles ¶
List available provider profiles and import new ones:
profiles, err := client.Providers().Profiles().List(ctx, "default")
if err != nil {
log.Fatal(err)
}
for _, p := range profiles {
fmt.Printf("%s (%s): %s\n", p.DisplayName, p.Category, p.Description)
}
result, err := client.Providers().Profiles().Import(ctx, "default", []v1.ProfileImportItem{
{Source: "openai-profile.yaml", Profile: v1.ProviderProfile{
DisplayName: "OpenAI",
Category: v1.ProfileCategoryInference,
}},
})
if err != nil {
log.Fatal(err)
}
for _, d := range result.Diagnostics {
fmt.Printf("[%s] %s: %s\n", d.Severity, d.Field, d.Message)
}
Credential Refresh ¶
Configure gateway-owned credential refresh for a provider:
status, err := client.Providers().Refresh().Configure(ctx, "default", &v1.RefreshConfig{
Provider: "openai",
CredentialKey: "api-key",
Strategy: v1.RefreshStrategyOAuth2ClientCredentials,
Material: map[string]string{"client_id": "xxx", "client_secret": "yyy"},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Refresh status: %s (next: %s)\n", status.Status, status.NextRefreshAt)
Token Refresh ¶
Use RefreshableToken for automatic OAuth2 token caching and refresh. Concurrent callers share a single refresh call:
tokenSource := oauth2Config.TokenSource(ctx, initialToken)
auth, err := v1.RefreshableToken(tokenSource,
v1.WithLeeway(30*time.Second),
)
if err != nil {
log.Fatal(err)
}
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: auth,
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
Extra Headers ¶
Use WithExtraHeaders to attach additional per-RPC headers to any auth provider. This is useful for edge proxies, API gateways, or any middleware that requires custom headers alongside standard authentication:
base := v1.StaticToken("my-token")
auth, err := v1.WithExtraHeaders(base, map[string]string{
"x-proxy-key": "proxy-secret",
"x-tenant-id": "acme-corp",
})
if err != nil {
log.Fatal(err)
}
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: auth,
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
Keys are normalized to lowercase (per HTTP/2 RFC 9113). On key collision, extra headers take precedence over base auth headers. Empty-string values are silently dropped. WithExtraHeaders composes with any AuthProvider, including RefreshableToken:
tokenSource := oauth2Config.TokenSource(ctx, initialToken)
refreshAuth, err := v1.RefreshableToken(tokenSource)
if err != nil {
log.Fatal(err)
}
auth, err := v1.WithExtraHeaders(refreshAuth, map[string]string{
"x-proxy-key": "proxy-secret",
})
SSH Session Management ¶
Create an SSH session for a sandbox and use the returned connection details. Note: CreateSession accepts a sandbox ID, not a name. For name-based access with automatic session cleanup, prefer SSH().Tunnel() instead.
session, err := client.SSH().CreateSession(ctx, "default", sandbox.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("SSH to %s:%d (scheme: %s)\n",
session.GatewayHost, session.GatewayPort, session.GatewayScheme)
fmt.Printf("Host key: %s\n", session.HostKeyFingerprint)
// Use session.Token to authenticate the SSH connection.
revoked, err := client.SSH().RevokeSession(ctx, "default", session.Token)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Session revoked: %v\n", revoked)
TCP Port Forwarding ¶
Forward a local connection to a port inside a sandbox:
conn, err := client.TCP().Forward(ctx, "default", "my-sandbox", 5432)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// conn implements io.ReadWriteCloser, use it like a net.Conn.
_, err = conn.Write([]byte("PING\n"))
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %s\n", buf[:n])
Use WithForwardServiceID to tag the forwarding session with a service identifier for audit logging:
conn, err := client.TCP().Forward(ctx, "default", "my-sandbox", 5432,
v1.WithForwardServiceID("billing-db"),
)
SSH Tunneling ¶
Create an SSH tunnel to a sandbox port in a single call. Tunnel combines session creation, TCP forwarding with an SSH relay target, and automatic session cleanup into one operation:
tunnel, err := client.SSH().Tunnel(ctx, "default", "my-sandbox", 22)
if err != nil {
log.Fatal(err)
}
defer tunnel.Close()
// tunnel implements io.ReadWriteCloser. The underlying SSH session
// is automatically revoked when Close is called.
_, err = tunnel.Write([]byte("SSH-2.0-client\r\n"))
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 256)
n, err := tunnel.Read(buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Server banner: %s\n", buf[:n])
Use WithTunnelServiceID to associate a service identifier with the tunnel:
tunnel, err := client.SSH().Tunnel(ctx, "default", "my-sandbox", 22,
v1.WithTunnelServiceID("dev-ssh"),
)
Sandbox Policy ¶
Set an initial security policy when creating a sandbox:
sandbox, err := client.Sandboxes().Create(ctx, "default", "secure-sandbox", &v1.SandboxSpec{
Template: &v1.SandboxTemplate{Image: "python:3.12"},
Policy: &v1.SandboxPolicy{
Version: 1,
Filesystem: &v1.FilesystemPolicy{
IncludeWorkdir: true,
ReadOnly: []string{"/usr", "/lib"},
},
Process: &v1.ProcessPolicy{
RunAsUser: "sandbox",
RunAsGroup: "sandbox",
},
NetworkPolicies: map[string]v1.NetworkPolicyRule{
"allow-api": {
Name: "allow-api",
Endpoints: []v1.PolicyNetworkEndpoint{
{Host: "api.example.com", Port: 443, Protocol: "tcp"},
},
},
},
},
}, nil)
Replace the full policy at runtime via configuration update:
result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
Name: "secure-sandbox",
Policy: &v1.SandboxPolicy{
Version: 2,
NetworkPolicies: map[string]v1.NetworkPolicyRule{
"allow-all": {Name: "allow-all"},
},
},
})
Read a policy back from revision history:
revisions, err := client.Policy().List(ctx, "default")
if err != nil {
log.Fatal(err)
}
for _, rev := range revisions {
if rev.Policy != nil {
fmt.Printf("v%d: %d network rules\n", rev.Version, len(rev.Policy.NetworkPolicies))
}
}
Global Policy ¶
List gateway-global policy revisions (no sandbox name or workspace needed):
revisions, err := client.Policy().List(ctx, "", v1.WithListGlobal(true))
if err != nil {
log.Fatal(err)
}
for _, rev := range revisions {
fmt.Printf("Global v%d: %s\n", rev.Version, rev.Status)
}
Get the status of a specific global policy version:
status, err := client.Policy().GetStatus(ctx, "", "",
v1.WithStatusGlobal(true), v1.WithVersion(3),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Version %d status: %s\n", status.Revision.Version, status.Revision.Status)
Workspace Management ¶
Create and manage workspaces for multi-tenant resource isolation:
ws, err := client.Workspaces().Create(ctx, "team-alpha", map[string]string{
"team": "alpha",
"env": "production",
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Workspace %s created (phase: %s)\n", ws.Name, ws.Phase)
workspaces, err := client.Workspaces().List(ctx)
if err != nil {
log.Fatal(err)
}
for _, w := range workspaces {
fmt.Printf(" %s (phase: %s)\n", w.Name, w.Phase)
}
Workspace Members ¶
Manage workspace membership with role-based access:
member, err := client.Workspaces().AddMember(ctx, "team-alpha",
"alice@example.com", v1.WorkspaceRoleAdmin)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Added %s as %s\n", member.PrincipalSubject, member.Role)
members, err := client.Workspaces().ListMembers(ctx, "team-alpha")
if err != nil {
log.Fatal(err)
}
for _, m := range members {
fmt.Printf(" %s (%s)\n", m.PrincipalSubject, m.Role)
}
Gateway Info ¶
Query gateway metadata and compute driver capabilities:
info, err := client.Health().GetGatewayInfo(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gateway %s (status: %s)\n", info.Version, info.Status)
for _, d := range info.ComputeDrivers {
fmt.Printf(" Driver: %s %s\n", d.DriverName, d.DriverVersion)
}
Current User ¶
Determine the identity of the authenticated caller:
user, err := client.Health().GetCurrentUser(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Logged in as %s (%s)\n", user.DisplayName, user.Subject)
fmt.Printf("Roles: %v, Scopes: %v\n", user.Roles, user.Scopes)
Configuration Management ¶
Read sandbox and gateway configuration, and update settings:
sbCfg, err := client.Config().GetSandbox(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Config revision: %d\n", sbCfg.ConfigRevision)
for name, setting := range sbCfg.Settings {
fmt.Printf(" %s = %v (scope: %s)\n", name, setting.Value, setting.Scope)
}
gwCfg, err := client.Config().GetGateway(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gateway settings revision: %d\n", gwCfg.SettingsRevision)
result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
Name: "my-sandbox",
SettingKey: "max_tokens",
SettingValue: &v1.SettingValue{
Type: v1.SettingValueInt,
IntVal: 8192,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("New settings revision: %d\n", result.SettingsRevision)
Inference Route Management ¶
Configure workspace-scoped inference routing to control how inference requests are forwarded to upstream providers:
route, err := client.Inference().SetRoute(ctx, "my-workspace", &v1.InferenceRouteConfig{
ProviderName: "openai",
ModelID: "gpt-4",
RouteName: "", // empty string = default route
TimeoutSecs: 120,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Route v%d: %s/%s\n", route.Version, route.ProviderName, route.ModelID)
route, err = client.Inference().GetRoute(ctx, "my-workspace", "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Provider: %s, Model: %s\n", route.ProviderName, route.ModelID)
err = client.Inference().DeleteRoute(ctx, "my-workspace", "")
if err != nil {
log.Fatal(err)
}
Package v1 provides the OpenShell SDK client. gRPC error conversion is handled by the internal/converter package.
Index ¶
- Constants
- Variables
- func IsAlreadyExists(err error) bool
- func IsCancelled(err error) bool
- func IsConflict(err error) bool
- func IsDeadlineExceeded(err error) bool
- func IsInvalidArgument(err error) bool
- func IsNotFound(err error) bool
- func IsPermissionDenied(err error) bool
- func IsUnauthenticated(err error) bool
- func IsUnavailable(err error) bool
- func IsUnimplemented(err error) bool
- type AddAllowRules
- type AddDenyRules
- type AddNetworkRule
- type ApproveAllOption
- type ApproveAllResult
- type ApproveResult
- type AttachProviderResult
- type AuthProvider
- type ClearResult
- type Client
- func (c *Client) Close() error
- func (c *Client) Config() ConfigInterface
- func (c *Client) Exec() ExecInterface
- func (c *Client) Files() FileInterface
- func (c *Client) Health() HealthInterface
- func (c *Client) Inference() InferenceInterface
- func (c *Client) Policy() PolicyInterface
- func (c *Client) Providers() ProviderInterface
- func (c *Client) SSH() SSHInterface
- func (c *Client) Sandboxes() SandboxInterface
- func (c *Client) Services() ServiceInterface
- func (c *Client) TCP() TCPInterface
- func (c *Client) Workspaces() WorkspaceInterface
- type ClientInterface
- type ComputeDriverInfo
- type Config
- type ConfigInterface
- type ConfigUpdate
- type ConfigUpdateResult
- type CreateOptions
- type CurrentUser
- type DeleteOptions
- type DetachProviderResult
- type DraftHistoryEntry
- type DraftPolicy
- type EffectiveSetting
- type ErrorCode
- type Event
- type EventType
- type ExecChunk
- type ExecInterface
- type ExecOptions
- type ExecResult
- type ExecStream
- type FileInterface
- type FilesystemPolicy
- type ForwardOption
- type GatewayConfig
- type GatewayInfo
- type GetDraftOption
- type GetOptions
- type GetStatusOption
- type GraphqlOperation
- type HealthInterface
- type HealthResult
- type ImportResult
- type InferenceInterface
- type InferenceRoute
- type InferenceRouteConfig
- type InteractiveSession
- type L7Allow
- type L7DenyRule
- type L7QueryMatcher
- type L7Rule
- type LandlockPolicy
- type LintResult
- type ListOptions
- type ListPolicyOption
- type ListenOption
- type LogLine
- type LogOption
- type LogResult
- type Logger
- type NetworkBinary
- type NetworkEndpoint
- type NetworkPolicyRule
- type PolicyChunk
- type PolicyInterface
- type PolicyLoadStatus
- type PolicyMergeOperation
- type PolicyNetworkBinary
- type PolicyNetworkEndpoint
- type PolicySource
- type PolicyStatusResult
- type ProcessPolicy
- type ProfileCategory
- type ProfileCredential
- type ProfileDiagnostic
- type ProfileDiscovery
- type ProfileImportItem
- type ProfileInterface
- type Provider
- type ProviderInterface
- type ProviderProfile
- type ProviderSpec
- type RefreshConfig
- type RefreshInterface
- type RefreshOption
- type RefreshStatus
- type RefreshStrategy
- type RemoveNetworkBinary
- type RemoveNetworkEndpoint
- type RemoveNetworkRule
- type RetryPolicy
- type SSHInterface
- type SSHSession
- type Sandbox
- type SandboxCondition
- type SandboxConfig
- type SandboxInterface
- type SandboxPhase
- type SandboxPolicy
- type SandboxPolicyRevision
- type SandboxSpec
- type SandboxStatus
- type SandboxTemplate
- type ServiceEndpoint
- type ServiceInterface
- type ServiceStatus
- type SettingScope
- type SettingValue
- type SettingValueType
- type StatusError
- type StreamType
- type TCPInterface
- type TLSConfig
- type TunnelOption
- type UndoResult
- type UpdateOptions
- type UpdateResult
- type ValidatedEndpoint
- type WaitOptions
- type WatchInterface
- type WatchOptions
- type Workspace
- type WorkspaceInterface
- type WorkspaceMember
- type WorkspacePhase
- type WorkspaceRole
Examples ¶
Constants ¶
const ( SettingValueString = types.SettingValueString SettingValueBool = types.SettingValueBool SettingValueInt = types.SettingValueInt SettingValueBytes = types.SettingValueBytes )
SettingValueType constants re-exported from types package.
const ( SettingScopeUnspecified = types.SettingScopeUnspecified SettingScopeSandbox = types.SettingScopeSandbox SettingScopeGlobal = types.SettingScopeGlobal )
SettingScope constants re-exported from types package.
const ( PolicySourceUnspecified = types.PolicySourceUnspecified PolicySourceSandbox = types.PolicySourceSandbox PolicySourceGlobal = types.PolicySourceGlobal )
PolicySource constants re-exported from types package.
const ( ErrorNotFound = types.ErrorNotFound ErrorAlreadyExists = types.ErrorAlreadyExists ErrorPermissionDenied = types.ErrorPermissionDenied ErrorInvalidArgument = types.ErrorInvalidArgument ErrorDeadlineExceeded = types.ErrorDeadlineExceeded ErrorCancelled = types.ErrorCancelled ErrorInternal = types.ErrorInternal ErrorUnimplemented = types.ErrorUnimplemented ErrorConflict = types.ErrorConflict ErrorUnauthenticated = types.ErrorUnauthenticated )
ErrorCode values for classifying gRPC errors.
const ( ServiceStatusHealthy = types.ServiceStatusHealthy ServiceStatusDegraded = types.ServiceStatusDegraded ServiceStatusUnhealthy = types.ServiceStatusUnhealthy ServiceStatusUnknown = types.ServiceStatusUnknown )
ServiceStatus constants.
const ( PolicyLoadStatusUnspecified = types.PolicyLoadStatusUnspecified PolicyLoadStatusPending = types.PolicyLoadStatusPending PolicyLoadStatusLoaded = types.PolicyLoadStatusLoaded PolicyLoadStatusFailed = types.PolicyLoadStatusFailed PolicyLoadStatusSuperseded = types.PolicyLoadStatusSuperseded )
PolicyLoadStatus constants re-exported from types package.
const ( ProfileCategoryOther = types.ProfileCategoryOther ProfileCategoryInference = types.ProfileCategoryInference ProfileCategoryAgent = types.ProfileCategoryAgent ProfileCategorySourceControl = types.ProfileCategorySourceControl ProfileCategoryMessaging = types.ProfileCategoryMessaging ProfileCategoryData = types.ProfileCategoryData ProfileCategoryKnowledge = types.ProfileCategoryKnowledge )
ProfileCategory values.
const ( RefreshStrategyStatic = types.RefreshStrategyStatic RefreshStrategyExternal = types.RefreshStrategyExternal RefreshStrategyOAuth2RefreshToken = types.RefreshStrategyOAuth2RefreshToken RefreshStrategyOAuth2ClientCredentials = types.RefreshStrategyOAuth2ClientCredentials RefreshStrategyGoogleServiceAccountJWT = types.RefreshStrategyGoogleServiceAccountJWT )
RefreshStrategy values.
const ( SandboxProvisioning = types.SandboxProvisioning SandboxReady = types.SandboxReady SandboxError = types.SandboxError SandboxDeleting = types.SandboxDeleting SandboxUnknown = types.SandboxUnknown )
SandboxPhase values for sandbox lifecycle.
const ( EventAdded = types.EventAdded EventModified = types.EventModified EventDeleted = types.EventDeleted EventError = types.EventError )
EventType values for watch events.
const ( StreamStdout = types.StreamStdout StreamStderr = types.StreamStderr )
StreamType values for exec output.
const ( WorkspaceActive = types.WorkspaceActive WorkspaceTerminating = types.WorkspaceTerminating WorkspaceUnknown = types.WorkspaceUnknown )
WorkspacePhase constants.
const ( WorkspaceRoleAdmin = types.WorkspaceRoleAdmin WorkspaceRoleUser = types.WorkspaceRoleUser WorkspaceRoleUnknown = types.WorkspaceRoleUnknown )
WorkspaceRole constants.
Variables ¶
var WithIncludeSecurityFlagged = types.WithIncludeSecurityFlagged
WithIncludeSecurityFlagged includes security-flagged chunks in bulk approval.
var WithLimit = types.WithLimit
WithLimit sets the maximum number of revisions to return.
var WithListGlobal = types.WithListGlobal
WithListGlobal enables global policy mode on List. When true, the query retrieves gateway-global policy revisions instead of sandbox-scoped ones.
var WithLogLines = types.WithLogLines
WithLogLines sets the maximum number of log lines to return.
var WithLogMinLevel = types.WithLogMinLevel
WithLogMinLevel sets the minimum log level to include.
var WithLogSince = types.WithLogSince
WithLogSince filters logs to entries at or after the given time.
var WithLogSources = types.WithLogSources
WithLogSources filters logs by source (e.g., "gateway", "sandbox").
var WithOffset = types.WithOffset
WithOffset sets the pagination offset.
var WithStatusFilter = types.WithStatusFilter
WithStatusFilter filters draft chunks by approval status.
var WithStatusGlobal = types.WithStatusGlobal
WithStatusGlobal enables global policy mode on GetStatus. When true, the query retrieves gateway-global policy status instead of sandbox-scoped status.
var WithVersion = types.WithVersion
WithVersion queries a specific policy version instead of the latest.
Functions ¶
func IsAlreadyExists ¶
IsAlreadyExists returns true if the error indicates a resource already exists.
Example ¶
ExampleIsAlreadyExists demonstrates handling a duplicate-creation error.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Create a sandbox
_, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
if err != nil {
log.Fatal(err)
}
// Try to create the same sandbox again
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
if v1.IsAlreadyExists(err) {
fmt.Println("Sandbox already exists")
}
}
Output: Sandbox already exists
func IsCancelled ¶
IsCancelled returns true if the error indicates the operation was cancelled.
func IsConflict ¶
IsConflict returns true if the error indicates a conflict, such as optimistic concurrency or an invalid state transition.
func IsDeadlineExceeded ¶
IsDeadlineExceeded returns true if the error indicates a deadline was exceeded.
func IsInvalidArgument ¶
IsInvalidArgument returns true if the error indicates an invalid argument.
func IsNotFound ¶
IsNotFound returns true if the error indicates a resource was not found.
Example ¶
ExampleIsNotFound demonstrates handling a not-found error.
package main
import (
"context"
"fmt"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
_, err := client.Sandboxes().Get(ctx, "default", "nonexistent")
if v1.IsNotFound(err) {
fmt.Println("Sandbox not found")
}
}
Output: Sandbox not found
func IsPermissionDenied ¶
IsPermissionDenied returns true if the error indicates insufficient permissions.
func IsUnauthenticated ¶ added in v0.3.0
IsUnauthenticated returns true if the error indicates invalid or missing credentials.
func IsUnavailable ¶
IsUnavailable returns true if the error indicates the service is unavailable.
func IsUnimplemented ¶
IsUnimplemented returns true if the error indicates the operation is not implemented.
Types ¶
type AddAllowRules ¶
type AddAllowRules = types.AddAllowRules
AddAllowRules appends layer-7 allow rules to a specific endpoint.
type AddDenyRules ¶
type AddDenyRules = types.AddDenyRules
AddDenyRules appends layer-7 deny rules to a specific endpoint.
type AddNetworkRule ¶
type AddNetworkRule = types.AddNetworkRule
AddNetworkRule adds a named network policy rule with a full rule definition.
type ApproveAllOption ¶
type ApproveAllOption = types.ApproveAllOption
ApproveAllOption configures an ApproveAllDraftChunks call.
type ApproveAllResult ¶
type ApproveAllResult = types.ApproveAllResult
ApproveAllResult contains the result of approving all draft chunks.
type ApproveResult ¶
type ApproveResult = types.ApproveResult
ApproveResult contains the result of approving a single draft chunk.
type AttachProviderResult ¶
type AttachProviderResult = types.AttachProviderResult
AttachProviderResult holds the result of attaching a provider to a sandbox.
type AuthProvider ¶
type AuthProvider = types.AuthProvider
AuthProvider supplies per-RPC credentials. It implements the grpc credentials.PerRPCCredentials interface.
func RefreshableToken ¶ added in v0.3.0
func RefreshableToken(src oauth2.TokenSource, opts ...RefreshOption) (AuthProvider, error)
RefreshableToken returns an AuthProvider that caches tokens from src and refreshes them before expiry. Concurrent callers share a single refresh call (coalesced via RWMutex double-checked locking).
func StaticToken ¶
func StaticToken(token string) AuthProvider
StaticToken returns an AuthProvider that sends a fixed Bearer token.
func WithExtraHeaders ¶ added in v0.3.0
func WithExtraHeaders(base AuthProvider, headers map[string]string) (AuthProvider, error)
WithExtraHeaders wraps base with additional per-RPC headers. Keys are normalized to lowercase per HTTP/2 (RFC 9113). Empty-string values are silently dropped. The headers map is deep-copied at construction time, so later mutations to the caller's map have no effect.
Returns an error if base is nil or if headers is nil, empty, or contains only empty-string values.
type ClearResult ¶
type ClearResult = types.ClearResult
ClearResult contains the result of clearing all draft chunks.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client implements ClientInterface. It holds a gRPC connection and provides sub-client accessors following the Kubernetes client-go pattern.
func NewClient ¶
NewClient creates a new SDK client connected to the given gateway.
Example (AddProvider) ¶
ExampleNewClient_addProvider demonstrates pre-seeding a fake client with a provider fixture.
package main
import (
"context"
"fmt"
"log"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
"github.com/rhuss/openshell-sdk-go/openshell/v1/types"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
// Pre-seed a provider
client.AddProvider("default", &types.Provider{
Name: "seeded-provider",
Type: "openai",
})
ctx := context.Background()
providers, err := client.Providers().List(ctx, "default")
if err != nil {
log.Fatal(err)
}
fmt.Println("Count:", len(providers))
fmt.Println("Name:", providers[0].Name)
}
Output: Count: 1 Name: seeded-provider
Example (AddSandbox) ¶
ExampleNewClient_addSandbox demonstrates pre-seeding a fake client with a sandbox fixture.
package main
import (
"context"
"fmt"
"log"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
"github.com/rhuss/openshell-sdk-go/openshell/v1/types"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
// Pre-seed a sandbox that already exists in Ready state
client.AddSandbox("default", &types.Sandbox{
Name: "pre-existing",
Status: types.SandboxStatus{
Phase: types.SandboxReady,
},
ResourceVersion: 5,
})
ctx := context.Background()
sb, err := client.Sandboxes().Get(ctx, "default", "pre-existing")
if err != nil {
log.Fatal(err)
}
fmt.Println("Name:", sb.Name)
fmt.Println("Phase:", sb.Status.Phase)
}
Output: Name: pre-existing Phase: Ready
Example (InferenceRoute) ¶
ExampleNewClient_inferenceRoute demonstrates setting and retrieving an inference route using the fake client.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Set an inference route for a workspace
route, err := client.Inference().SetRoute(ctx, "my-workspace", &v1.InferenceRouteConfig{
ProviderName: "openai",
ModelID: "gpt-4",
RouteName: "",
TimeoutSecs: 120,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Set route v%d: %s/%s\n", route.Version, route.ProviderName, route.ModelID)
// Retrieve the route
route, err = client.Inference().GetRoute(ctx, "my-workspace", "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Got route: %s/%s (timeout: %ds)\n", route.ProviderName, route.ModelID, route.TimeoutSecs)
// Delete the route
err = client.Inference().DeleteRoute(ctx, "my-workspace", "")
if err != nil {
log.Fatal(err)
}
// Verify deletion
_, err = client.Inference().GetRoute(ctx, "my-workspace", "")
fmt.Println("After delete:", v1.IsNotFound(err))
}
Output: Set route v1: openai/gpt-4 Got route: openai/gpt-4 (timeout: 120s) After delete: true
Example (StopOnTerminal) ¶
ExampleNewClient_stopOnTerminal demonstrates the StopOnTerminal watch option that automatically closes the watcher when a sandbox reaches a terminal phase.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Watch with StopOnTerminal
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox", v1.WatchOptions{
StopOnTerminal: true,
})
if err != nil {
log.Fatal(err)
}
// Create and transition to Ready
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
if err != nil {
log.Fatal(err)
}
_, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
// Drain events, channel closes after terminal phase
var count int
for range watcher.ResultChan() {
count++
}
fmt.Println("Events received:", count)
}
Output: Events received: 2
Example (WatchEvents) ¶
ExampleNewClient_watchEvents demonstrates watching for sandbox events using the fake client.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Start watching before creating
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
defer watcher.Stop()
// Create triggers an ADDED event
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
if err != nil {
log.Fatal(err)
}
event := <-watcher.ResultChan()
fmt.Println("Type:", event.Type)
fmt.Println("Name:", event.Object.Name)
}
Output: Type: ADDED Name: my-sandbox
Example (WithHealthResult) ¶
ExampleNewClient_withHealthResult demonstrates configuring the fake health sub-client to return a custom result.
package main
import (
"context"
"fmt"
"log"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
"github.com/rhuss/openshell-sdk-go/openshell/v1/types"
)
func main() {
client := fake.NewClient(fake.WithHealthResult(&types.HealthResult{
Healthy: false,
Version: "1.2.3",
}))
defer client.Close() //nolint:errcheck
ctx := context.Background()
result, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Healthy:", result.Healthy)
fmt.Println("Version:", result.Version)
}
Output: Healthy: false Version: 1.2.3
func (*Client) Config ¶
func (c *Client) Config() ConfigInterface
Config returns the configuration sub-client.
func (*Client) Exec ¶
func (c *Client) Exec() ExecInterface
Exec returns the exec sub-client.
Example ¶
ExampleClient_Exec demonstrates running a command in a sandbox. The fake client returns Unimplemented for exec operations, so this example shows the call pattern and error handling.
package main
import (
"context"
"fmt"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
_, err := client.Exec().Run(ctx, "default", "my-sandbox", []string{"echo", "hello"})
if v1.IsUnimplemented(err) {
fmt.Println("Exec requires a real gateway")
}
}
Output: Exec requires a real gateway
func (*Client) Health ¶
func (c *Client) Health() HealthInterface
Health returns the health sub-client.
Example ¶
ExampleClient_Health demonstrates checking gateway health.
package main
import (
"context"
"fmt"
"log"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
result, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Healthy:", result.Healthy)
}
Output: Healthy: true
func (*Client) Inference ¶ added in v0.3.0
func (c *Client) Inference() InferenceInterface
Inference returns the inference route management sub-client.
func (*Client) Policy ¶
func (c *Client) Policy() PolicyInterface
Policy returns the policy management sub-client.
func (*Client) Providers ¶
func (c *Client) Providers() ProviderInterface
Providers returns the provider sub-client.
Example ¶
ExampleClient_Providers demonstrates registering and listing providers.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Register a provider
_, err := client.Providers().Create(ctx, "default", &v1.Provider{
Name: "my-openai",
Type: "openai",
})
if err != nil {
log.Fatal(err)
}
// List all providers
providers, err := client.Providers().List(ctx, "default")
if err != nil {
log.Fatal(err)
}
fmt.Println("Count:", len(providers))
fmt.Println("Name:", providers[0].Name)
}
Output: Count: 1 Name: my-openai
func (*Client) Sandboxes ¶
func (c *Client) Sandboxes() SandboxInterface
Sandboxes returns the sandbox sub-client.
Example ¶
ExampleClient_Sandboxes demonstrates the sandbox lifecycle: create a sandbox, wait for it to become ready, and then clean up.
package main
import (
"context"
"fmt"
"log"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Create a sandbox
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Phase after create:", sb.Status.Phase)
// Wait for the sandbox to become ready
sb, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Println("Phase after wait:", sb.Status.Phase)
// Clean up
if err := client.Sandboxes().Delete(ctx, "default", "my-sandbox"); err != nil {
log.Fatal(err)
}
fmt.Println("Deleted")
}
Output: Phase after create: Provisioning Phase after wait: Ready Deleted
func (*Client) Services ¶
func (c *Client) Services() ServiceInterface
Services returns the service sub-client.
func (*Client) TCP ¶
func (c *Client) TCP() TCPInterface
TCP returns the TCP port forwarding sub-client.
Example ¶
ExampleClient_TCP demonstrates binding a local port to a sandbox port using the net.Listener pattern. The returned listener tunnels every accepted connection to the remote port inside the sandbox.
The fake client returns Unimplemented for Listen, so this example shows the call pattern and error handling rather than a live tunnel.
package main
import (
"context"
"fmt"
v1 "github.com/rhuss/openshell-sdk-go/openshell/v1"
"github.com/rhuss/openshell-sdk-go/openshell/v1/fake"
)
func main() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Bind local port 0 (OS-assigned) to sandbox port 8080.
ln, err := client.TCP().Listen(ctx, "default", "my-sandbox", 8080, 0)
if v1.IsUnimplemented(err) {
fmt.Println("Listen requires a real gateway")
}
if ln != nil {
// In production, use ln.Addr() to discover the assigned port,
// then accept connections in a loop:
//
// for {
// conn, err := ln.Accept()
// if err != nil { break }
// go handleConn(conn)
// }
defer ln.Close() //nolint:errcheck
}
}
Output: Listen requires a real gateway
func (*Client) Workspaces ¶ added in v0.3.0
func (c *Client) Workspaces() WorkspaceInterface
Workspaces returns the workspace management sub-client.
type ClientInterface ¶
type ClientInterface interface {
Sandboxes() SandboxInterface
Providers() ProviderInterface
Services() ServiceInterface
Exec() ExecInterface
Files() FileInterface
Health() HealthInterface
SSH() SSHInterface
TCP() TCPInterface
Config() ConfigInterface
Policy() PolicyInterface
Workspaces() WorkspaceInterface
Inference() InferenceInterface
Close() error
}
ClientInterface defines the top-level SDK surface.
type ComputeDriverInfo ¶ added in v0.3.0
type ComputeDriverInfo = types.ComputeDriverInfo
ComputeDriverInfo describes a compute backend available on the gateway.
type ConfigInterface ¶
type ConfigInterface interface {
GetSandbox(ctx context.Context, workspace, sandboxName string) (*SandboxConfig, error)
GetGateway(ctx context.Context) (*GatewayConfig, error)
Update(ctx context.Context, workspace string, update *ConfigUpdate) (*ConfigUpdateResult, error)
}
ConfigInterface defines operations for reading and updating gateway and sandbox configuration.
type ConfigUpdate ¶
type ConfigUpdate = types.ConfigUpdate
ConfigUpdate represents a configuration mutation request.
type ConfigUpdateResult ¶
type ConfigUpdateResult = types.ConfigUpdateResult
ConfigUpdateResult holds the result of a configuration update operation.
type CreateOptions ¶
type CreateOptions = types.CreateOptions
CreateOptions configures resource creation.
type CurrentUser ¶ added in v0.3.0
type CurrentUser = types.CurrentUser
CurrentUser holds the authenticated caller's identity.
type DeleteOptions ¶
type DeleteOptions = types.DeleteOptions
DeleteOptions configures resource deletion.
type DetachProviderResult ¶
type DetachProviderResult = types.DetachProviderResult
DetachProviderResult holds the result of detaching a provider from a sandbox.
type DraftHistoryEntry ¶
type DraftHistoryEntry = types.DraftHistoryEntry
DraftHistoryEntry represents a single event in the draft policy history.
type DraftPolicy ¶
type DraftPolicy = types.DraftPolicy
DraftPolicy contains the full draft policy state returned by GetDraft.
type EffectiveSetting ¶
type EffectiveSetting = types.EffectiveSetting
EffectiveSetting is a setting value paired with its resolved scope.
type ExecInterface ¶
type ExecInterface interface {
Run(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (*ExecResult, error)
Stream(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (ExecStream, error)
Interactive(ctx context.Context, workspace, sandboxName string, command []string, cols, rows uint32, opts ...ExecOptions) (InteractiveSession, error)
}
ExecInterface defines command execution operations on sandboxes. Methods accept a sandbox name and resolve it to an ID internally.
type ExecResult ¶
type ExecResult = types.ExecResult
ExecResult holds the collected output of a completed command execution.
type ExecStream ¶
ExecStream provides an iterator interface over streaming command output.
type FileInterface ¶
type FileInterface interface {
Upload(ctx context.Context, workspace, sandboxName string, localPath string, remotePath string) error
Download(ctx context.Context, workspace, sandboxName string, remotePath string, localPath string) error
}
FileInterface defines file transfer operations on sandboxes. Methods accept a sandbox name and resolve it to an ID internally.
type FilesystemPolicy ¶ added in v0.2.1
type FilesystemPolicy = types.FilesystemPolicy
FilesystemPolicy controls which directories the sandbox can access.
type ForwardOption ¶
type ForwardOption func(*forwardConfig)
ForwardOption configures a TCP forward opened via TCPInterface.Forward.
func WithForwardServiceID ¶
func WithForwardServiceID(id string) ForwardOption
WithForwardServiceID sets an optional service identifier on the forward's init frame for audit and correlation purposes.
type GatewayConfig ¶
type GatewayConfig = types.GatewayConfig
GatewayConfig represents gateway-global settings.
type GatewayInfo ¶ added in v0.3.0
type GatewayInfo = types.GatewayInfo
GatewayInfo holds operational metadata about the gateway.
type GetDraftOption ¶
type GetDraftOption = types.GetDraftOption
GetDraftOption configures a GetDraft call.
type GetStatusOption ¶
type GetStatusOption = types.GetStatusOption
GetStatusOption configures a GetStatus call.
type GraphqlOperation ¶
type GraphqlOperation = types.GraphqlOperation
GraphqlOperation describes a GraphQL operation for persisted-query validation.
type HealthInterface ¶
type HealthInterface interface {
Check(ctx context.Context) (*HealthResult, error)
GetGatewayInfo(ctx context.Context) (*GatewayInfo, error)
GetCurrentUser(ctx context.Context) (*CurrentUser, error)
}
HealthInterface defines health check and gateway info operations.
type HealthResult ¶
type HealthResult = types.HealthResult
HealthResult holds the result of a health check.
type ImportResult ¶
type ImportResult = types.ImportResult
ImportResult holds the result of a profile import operation.
type InferenceInterface ¶ added in v0.3.0
type InferenceInterface interface {
// SetRoute configures an inference route for a workspace.
// Returns ErrorInvalidArgument if workspace, providerName, or modelID is empty.
SetRoute(ctx context.Context, workspace string, config *InferenceRouteConfig) (*InferenceRoute, error)
// GetRoute retrieves the inference route for a workspace by route name.
// Returns ErrorInvalidArgument if workspace is empty.
// Returns ErrorNotFound if no route exists for the given name.
GetRoute(ctx context.Context, workspace, routeName string) (*InferenceRoute, error)
// DeleteRoute removes an inference route from a workspace.
// Returns ErrorInvalidArgument if workspace is empty.
// Idempotent: deleting a non-existent route is not an error.
DeleteRoute(ctx context.Context, workspace, routeName string) error
}
InferenceInterface defines inference route management operations. Accessed via client.Inference().
type InferenceRoute ¶ added in v0.3.0
type InferenceRoute = types.InferenceRoute
InferenceRoute represents a configured inference route as returned by the gateway.
type InferenceRouteConfig ¶ added in v0.3.0
type InferenceRouteConfig = types.InferenceRouteConfig
InferenceRouteConfig holds parameters for setting an inference route.
type InteractiveSession ¶
type InteractiveSession interface {
Read(p []byte) (int, error)
Write(p []byte) (int, error)
Resize(cols, rows uint32) error
ExitCode() (int, error)
Close() error
}
InteractiveSession provides bidirectional I/O for interactive command execution.
type L7DenyRule ¶
type L7DenyRule = types.L7DenyRule
L7DenyRule specifies layer-7 deny criteria for HTTP/GraphQL traffic.
type L7QueryMatcher ¶
type L7QueryMatcher = types.L7QueryMatcher
L7QueryMatcher matches query parameters by glob pattern or exact values.
type LandlockPolicy ¶ added in v0.2.1
type LandlockPolicy = types.LandlockPolicy
LandlockPolicy configures the Linux Landlock LSM.
type LintResult ¶
type LintResult = types.LintResult
LintResult holds the result of a profile lint operation.
type ListOptions ¶
type ListOptions = types.ListOptions
ListOptions configures resource listing with pagination and filtering.
type ListPolicyOption ¶
type ListPolicyOption = types.ListPolicyOption
ListPolicyOption configures a List call.
type ListenOption ¶ added in v0.3.0
type ListenOption func(*listenConfig)
ListenOption configures a local listener opened via TCPInterface.Listen.
func WithBindAddress ¶ added in v0.3.0
func WithBindAddress(addr string) ListenOption
WithBindAddress overrides the default local bind address ("127.0.0.1"). Pass "0.0.0.0" to accept connections from any interface.
func WithListenServiceID ¶ added in v0.3.0
func WithListenServiceID(id string) ListenOption
WithListenServiceID sets an optional service identifier on each tunneled connection's init frame for audit and correlation purposes.
func WithSSHTunnel ¶ added in v0.3.0
func WithSSHTunnel() ListenOption
WithSSHTunnel routes each accepted connection through an SSH tunnel (SSHInterface.Tunnel) instead of the default TCP forward (TCPInterface.Forward).
type Logger ¶
Logger defines structured logging for the SDK. Compatible with logr.Logger and slog.Logger adapters.
type NetworkBinary ¶
type NetworkBinary = types.NetworkBinary
NetworkBinary describes a binary artifact provided by a profile.
type NetworkEndpoint ¶
type NetworkEndpoint = types.NetworkEndpoint
NetworkEndpoint describes a network endpoint provided by a profile.
type NetworkPolicyRule ¶
type NetworkPolicyRule = types.NetworkPolicyRule
NetworkPolicyRule defines a named network policy rule containing endpoints and binaries.
type PolicyChunk ¶
type PolicyChunk = types.PolicyChunk
PolicyChunk represents a single proposed policy change in the draft inbox.
type PolicyInterface ¶
type PolicyInterface interface {
GetDraft(ctx context.Context, workspace, sandboxName string, opts ...GetDraftOption) (*DraftPolicy, error)
ApproveDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string) (*ApproveResult, error)
RejectDraftChunk(ctx context.Context, workspace, sandboxName, chunkID, reason string) error
ApproveAllDraftChunks(ctx context.Context, workspace, sandboxName string, opts ...ApproveAllOption) (*ApproveAllResult, error)
ClearDraftChunks(ctx context.Context, workspace, sandboxName string) (*ClearResult, error)
GetDraftHistory(ctx context.Context, workspace, sandboxName string) ([]DraftHistoryEntry, error)
GetStatus(ctx context.Context, workspace, sandboxName string, opts ...GetStatusOption) (*PolicyStatusResult, error)
List(ctx context.Context, workspace string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error)
EditDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string, proposedRule *NetworkPolicyRule) error
UndoDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string) (*UndoResult, error)
}
PolicyInterface defines operations for managing sandbox policy drafts, approvals, and revision history.
type PolicyLoadStatus ¶
type PolicyLoadStatus = types.PolicyLoadStatus
PolicyLoadStatus represents the load state of a policy revision.
type PolicyMergeOperation ¶
type PolicyMergeOperation = types.PolicyMergeOperation
PolicyMergeOperation represents a single atomic policy mutation.
type PolicyNetworkBinary ¶
type PolicyNetworkBinary = types.PolicyNetworkBinary
PolicyNetworkBinary identifies a binary subject to network policy enforcement.
type PolicyNetworkEndpoint ¶
type PolicyNetworkEndpoint = types.PolicyNetworkEndpoint
PolicyNetworkEndpoint describes a full network endpoint in a sandbox network policy rule.
type PolicySource ¶
type PolicySource = types.PolicySource
PolicySource indicates the source of a policy payload.
type PolicyStatusResult ¶
type PolicyStatusResult = types.PolicyStatusResult
PolicyStatusResult contains the status of a sandbox's policy.
type ProcessPolicy ¶ added in v0.2.1
type ProcessPolicy = types.ProcessPolicy
ProcessPolicy controls the user and group identity for sandboxed processes.
type ProfileCategory ¶
type ProfileCategory = types.ProfileCategory
ProfileCategory classifies a provider profile.
type ProfileCredential ¶
type ProfileCredential = types.ProfileCredential
ProfileCredential defines a single credential required by a provider profile.
type ProfileDiagnostic ¶
type ProfileDiagnostic = types.ProfileDiagnostic
ProfileDiagnostic is a validation finding from Import, Update, or Lint.
type ProfileDiscovery ¶
type ProfileDiscovery = types.ProfileDiscovery
ProfileDiscovery holds local discovery configuration for a profile.
type ProfileImportItem ¶
type ProfileImportItem = types.ProfileImportItem
ProfileImportItem is an item submitted for profile import or lint validation.
type ProfileInterface ¶
type ProfileInterface interface {
List(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error)
Get(ctx context.Context, workspace, id string) (*ProviderProfile, error)
Import(ctx context.Context, workspace string, items []ProfileImportItem) (*ImportResult, error)
Update(ctx context.Context, workspace, id string, expectedResourceVersion uint64, item ProfileImportItem) (*UpdateResult, error)
Lint(ctx context.Context, workspace string, items []ProfileImportItem) (*LintResult, error)
Delete(ctx context.Context, workspace, id string) (bool, error)
}
ProfileInterface defines operations for managing provider profiles.
type ProviderInterface ¶
type ProviderInterface interface {
Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
Get(ctx context.Context, workspace, name string) (*Provider, error)
List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error)
Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
Delete(ctx context.Context, workspace, name string) error
Ensure(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
Profiles() ProfileInterface
Refresh() RefreshInterface
}
ProviderInterface defines CRUD and Ensure operations on providers, plus sub-client accessors for profiles and credential refresh.
type ProviderProfile ¶
type ProviderProfile = types.ProviderProfile
ProviderProfile represents a provider type template.
type ProviderSpec ¶
type ProviderSpec = types.ProviderSpec
ProviderSpec holds provider-specific configuration and credentials.
type RefreshConfig ¶
type RefreshConfig = types.RefreshConfig
RefreshConfig holds configuration parameters for credential refresh.
type RefreshInterface ¶
type RefreshInterface interface {
GetStatus(ctx context.Context, workspace, provider, credentialKey string) ([]*RefreshStatus, error)
Configure(ctx context.Context, workspace string, config *RefreshConfig) (*RefreshStatus, error)
Rotate(ctx context.Context, workspace, provider, credentialKey string) (*RefreshStatus, error)
Delete(ctx context.Context, workspace, provider, credentialKey string) (bool, error)
}
RefreshInterface defines operations for managing provider credential refresh.
type RefreshOption ¶ added in v0.3.0
type RefreshOption func(*refreshConfig)
RefreshOption configures the behavior of RefreshableToken.
func WithLeeway ¶ added in v0.3.0
func WithLeeway(d time.Duration) RefreshOption
WithLeeway sets the duration before token expiry at which a proactive refresh is triggered. Default is 10 seconds.
func WithLogger ¶ added in v0.3.0
func WithLogger(l types.Logger) RefreshOption
WithLogger sets the logger used for stale-token fallback warnings. When not set, warnings are silently dropped.
type RefreshStatus ¶
type RefreshStatus = types.RefreshStatus
RefreshStatus reports the current state of credential refresh for a provider credential.
type RefreshStrategy ¶
type RefreshStrategy = types.RefreshStrategy
RefreshStrategy describes how credentials are refreshed.
type RemoveNetworkBinary ¶
type RemoveNetworkBinary = types.RemoveNetworkBinary
RemoveNetworkBinary removes a binary from a named rule.
type RemoveNetworkEndpoint ¶
type RemoveNetworkEndpoint = types.RemoveNetworkEndpoint
RemoveNetworkEndpoint removes a specific endpoint from a named rule.
type RemoveNetworkRule ¶
type RemoveNetworkRule = types.RemoveNetworkRule
RemoveNetworkRule removes an entire named rule from the policy.
type RetryPolicy ¶
type RetryPolicy = types.RetryPolicy
RetryPolicy configures automatic retry behavior for failed RPCs.
type SSHInterface ¶
type SSHInterface interface {
CreateSession(ctx context.Context, workspace, sandboxID string) (*SSHSession, error)
RevokeSession(ctx context.Context, workspace, token string) (bool, error)
Tunnel(ctx context.Context, workspace, sandboxName string, port uint32, opts ...TunnelOption) (io.ReadWriteCloser, error)
}
SSHInterface defines operations for managing SSH sessions.
type SSHSession ¶
type SSHSession = types.SSHSession
SSHSession represents an SSH session created for a sandbox.
type SandboxCondition ¶
type SandboxCondition = types.SandboxCondition
SandboxCondition describes an observed condition of a sandbox.
type SandboxConfig ¶
type SandboxConfig = types.SandboxConfig
SandboxConfig represents the full configuration state of a sandbox.
type SandboxInterface ¶
type SandboxInterface interface {
Create(ctx context.Context, workspace, name string, spec *SandboxSpec, labels map[string]string) (*Sandbox, error)
Get(ctx context.Context, workspace, name string) (*Sandbox, error)
List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error)
Delete(ctx context.Context, workspace, name string) error
AttachProvider(ctx context.Context, workspace, sandboxName, providerName string, expectedResourceVersion uint64) (*AttachProviderResult, error)
DetachProvider(ctx context.Context, workspace, sandboxName, providerName string, expectedResourceVersion uint64) (*DetachProviderResult, error)
ListProviders(ctx context.Context, workspace, sandboxName string) ([]*Provider, error)
WaitReady(ctx context.Context, workspace, name string, opts ...WaitOptions) (*Sandbox, error)
Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error)
GetLogs(ctx context.Context, workspace, sandboxName string, opts ...LogOption) (*LogResult, error)
}
SandboxInterface defines lifecycle operations on sandboxes.
type SandboxPhase ¶
type SandboxPhase = types.SandboxPhase
SandboxPhase represents the lifecycle phase of a sandbox.
type SandboxPolicy ¶ added in v0.2.1
type SandboxPolicy = types.SandboxPolicy
SandboxPolicy is the top-level security policy configuration for a sandbox.
type SandboxPolicyRevision ¶
type SandboxPolicyRevision = types.SandboxPolicyRevision
SandboxPolicyRevision represents a versioned policy revision for a sandbox.
type SandboxSpec ¶
type SandboxSpec = types.SandboxSpec
SandboxSpec holds the desired state of a sandbox.
type SandboxStatus ¶
type SandboxStatus = types.SandboxStatus
SandboxStatus holds the observed state of a sandbox.
type SandboxTemplate ¶
type SandboxTemplate = types.SandboxTemplate
SandboxTemplate defines the container template for a sandbox.
type ServiceEndpoint ¶
type ServiceEndpoint = types.ServiceEndpoint
ServiceEndpoint represents an exposed HTTP service endpoint within a sandbox.
type ServiceInterface ¶
type ServiceInterface interface {
Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool) (*ServiceEndpoint, error)
Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error)
List(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error)
Delete(ctx context.Context, workspace, sandboxName, serviceName string) error
}
ServiceInterface defines operations for managing sandbox service endpoints.
type ServiceStatus ¶ added in v0.3.0
type ServiceStatus = types.ServiceStatus
ServiceStatus describes the health state of the gateway.
type SettingScope ¶
type SettingScope = types.SettingScope
SettingScope indicates whether a setting is sandbox or global.
type SettingValue ¶
type SettingValue = types.SettingValue
SettingValue is a typed setting value (string, bool, int64, or bytes).
type SettingValueType ¶
type SettingValueType = types.SettingValueType
SettingValueType identifies which typed field of a SettingValue is active.
type StatusError ¶
type StatusError = types.StatusError
StatusError is the typed error returned by all SDK operations.
type StreamType ¶
type StreamType = types.StreamType
StreamType identifies which output stream a chunk belongs to.
type TCPInterface ¶
type TCPInterface interface {
Forward(ctx context.Context, workspace, sandboxName string, port uint32, opts ...ForwardOption) (io.ReadWriteCloser, error)
Listen(ctx context.Context, workspace, sandboxName string, remotePort uint32, localPort uint32, opts ...ListenOption) (net.Listener, error)
}
TCPInterface defines operations for TCP port forwarding to sandboxes. Methods accept a sandbox name and resolve it to an ID internally.
type TunnelOption ¶
type TunnelOption func(*tunnelConfig)
TunnelOption configures an SSH tunnel opened via SSHInterface.Tunnel.
func WithTunnelServiceID ¶
func WithTunnelServiceID(id string) TunnelOption
WithTunnelServiceID sets an optional service identifier on the tunnel's init frame for audit and correlation purposes.
type UndoResult ¶
type UndoResult = types.UndoResult
UndoResult contains the result of undoing a draft chunk approval.
type UpdateOptions ¶
type UpdateOptions = types.UpdateOptions
UpdateOptions configures resource updates.
type UpdateResult ¶
type UpdateResult = types.UpdateResult
UpdateResult holds the result of a profile update operation.
type ValidatedEndpoint ¶ added in v0.3.0
type ValidatedEndpoint = types.ValidatedEndpoint
ValidatedEndpoint represents an endpoint probed during route validation.
type WaitOptions ¶
type WaitOptions = types.WaitOptions
WaitOptions configures wait behavior. Use context for timeout control.
type WatchInterface ¶
type WatchInterface[T any] = types.WatchInterface[T]
WatchInterface delivers a stream of typed events. Modeled after k8s.io/apimachinery/pkg/watch.Interface.
type WorkspaceInterface ¶ added in v0.3.0
type WorkspaceInterface interface {
Create(ctx context.Context, name string, labels map[string]string) (*Workspace, error)
Get(ctx context.Context, name string) (*Workspace, error)
List(ctx context.Context, opts ...ListOptions) ([]*Workspace, error)
Delete(ctx context.Context, name string) error
AddMember(ctx context.Context, workspace, principalSubject string, role WorkspaceRole) (*WorkspaceMember, error)
RemoveMember(ctx context.Context, workspace, principalSubject string) error
ListMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error)
}
WorkspaceInterface defines workspace and member management operations.
type WorkspaceMember ¶ added in v0.3.0
type WorkspaceMember = types.WorkspaceMember
WorkspaceMember represents a user's membership in a workspace.
type WorkspacePhase ¶ added in v0.3.0
type WorkspacePhase = types.WorkspacePhase
WorkspacePhase describes the lifecycle state of a workspace.
type WorkspaceRole ¶ added in v0.3.0
type WorkspaceRole = types.WorkspaceRole
WorkspaceRole describes a member's role within a workspace.
Source Files
¶
- auth.go
- auth_extra.go
- auth_refresh.go
- client.go
- config.go
- config_client.go
- doc.go
- errors.go
- exec.go
- exec_client.go
- file.go
- file_client.go
- grpc_errors.go
- health.go
- health_client.go
- inference.go
- inference_client.go
- logger.go
- options.go
- policy.go
- policy_client.go
- profile.go
- profile_client.go
- provider.go
- provider_client.go
- refresh.go
- refresh_client.go
- sandbox.go
- sandbox_client.go
- service.go
- service_client.go
- ssh.go
- ssh_client.go
- tcp.go
- tcp_client.go
- types.go
- types_reexport.go
- watch.go
- workspace.go
- workspace_client.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package edge provides utilities for connecting to OpenShell gateways through edge proxies such as Cloudflare Access.
|
Package edge provides utilities for connecting to OpenShell gateways through edge proxies such as Cloudflare Access. |
|
Package fake provides an in-memory fake implementation of the OpenShell SDK client interfaces for use in consumer test suites.
|
Package fake provides an in-memory fake implementation of the OpenShell SDK client interfaces for use in consumer test suites. |
|
Package gateway reads on-disk gateway configurations created by the OpenShell Rust CLI and constructs fully wired SDK clients.
|
Package gateway reads on-disk gateway configurations created by the OpenShell Rust CLI and constructs fully wired SDK clients. |
|
internal
|
|
|
converter
Package converter maps between gRPC/proto types and SDK domain types.
|
Package converter maps between gRPC/proto types and SDK domain types. |
|
grpc
Package grpc provides gRPC connection setup utilities.
|
Package grpc provides gRPC connection setup utilities. |
|
Package oidc provides OIDC authentication flows for the OpenShell SDK.
|
Package oidc provides OIDC authentication flows for the OpenShell SDK. |
|
Package types defines all domain data types for the OpenShell SDK v1 API.
|
Package types defines all domain data types for the OpenShell SDK v1 API. |