v1

package
v0.0.0-...-277f922 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

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, and Workspaces). Network 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)
}

Pagination

List methods construct a lazy Pager without issuing an RPC. Each NextPage call fetches one page; ListAll is the explicit exhaustive convenience.

pages, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 100})
if err != nil {
    log.Fatal(err)
}
for {
    page, err := pages.NextPage(ctx)
    if err != nil {
        log.Fatal(err)
    }
    if page == nil {
        break
    }
    for _, sandbox := range page.Items {
        fmt.Println(sandbox.Name)
    }
}

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().ListAll(ctx, "default", "my-sandbox")
if err != nil {
    log.Fatal(err)
}
for _, ep := range endpoints {
    fmt.Printf("  %s → port %d (URL: %s)\n", ep.Name, ep.TargetPort, ep.URL)
}

Provider Profiles

List available provider profiles and import new ones:

profiles, err := client.Providers().Profiles().ListAll(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 by its canonical name in a workspace and use the returned connection details.

session, err := client.SSH().CreateSession(ctx, "default", sandbox.Name)
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.

deletion, err := client.SSH().RevokeSession(ctx, "default", session.Token)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Revocation outcome: %v\n", deletion.Outcome)

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().ListAll(ctx, "default", "my-sandbox")
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().ListAll(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().ListAll(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().ListAllMembers(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)

Index

Examples

Constants

View Source
const (
	SettingValueString = types.SettingValueString
	SettingValueBool   = types.SettingValueBool
	SettingValueInt    = types.SettingValueInt
	SettingValueBytes  = types.SettingValueBytes
)

SettingValueType constants re-exported from types package.

View Source
const (
	SettingScopeUnspecified = types.SettingScopeUnspecified
	SettingScopeSandbox     = types.SettingScopeSandbox
	SettingScopeGlobal      = types.SettingScopeGlobal
)

SettingScope constants re-exported from types package.

View Source
const (
	PolicySourceUnspecified = types.PolicySourceUnspecified
	PolicySourceSandbox     = types.PolicySourceSandbox
	PolicySourceGlobal      = types.PolicySourceGlobal
)

PolicySource constants re-exported from types package.

View Source
const (
	ErrorNotFound         = types.ErrorNotFound
	ErrorAlreadyExists    = types.ErrorAlreadyExists
	ErrorUnavailable      = types.ErrorUnavailable
	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.

View Source
const (
	ExtensionKindComputeDriver        = types.ExtensionKindComputeDriver
	ExtensionKindCredentialDriver     = types.ExtensionKindCredentialDriver
	ExtensionKindGatewayInterceptor   = types.ExtensionKindGatewayInterceptor
	ExtensionKindSupervisorMiddleware = types.ExtensionKindSupervisorMiddleware
	ExtensionKindUnknown              = types.ExtensionKindUnknown
)

ExtensionKind constants re-exported from the types package.

View Source
const (
	ServiceStatusHealthy   = types.ServiceStatusHealthy
	ServiceStatusDegraded  = types.ServiceStatusDegraded
	ServiceStatusUnhealthy = types.ServiceStatusUnhealthy
	ServiceStatusUnknown   = types.ServiceStatusUnknown
)

ServiceStatus constants.

View Source
const (
	DeletionUnspecified   = types.DeletionUnspecified
	DeletionCompleted     = types.DeletionCompleted
	DeletionAccepted      = types.DeletionAccepted
	DeletionAlreadyAbsent = types.DeletionAlreadyAbsent
)

Known deletion outcomes. Unrecognized values do not establish completion.

View Source
const (
	PolicyLoadStatusUnspecified = types.PolicyLoadStatusUnspecified
	PolicyLoadStatusPending     = types.PolicyLoadStatusPending
	PolicyLoadStatusLoaded      = types.PolicyLoadStatusLoaded
	PolicyLoadStatusFailed      = types.PolicyLoadStatusFailed
	PolicyLoadStatusSuperseded  = types.PolicyLoadStatusSuperseded
)

PolicyLoadStatus constants re-exported from types package.

View Source
const (
	ProfileCategoryOther         = types.ProfileCategoryOther
	ProfileCategoryInference     = types.ProfileCategoryInference
	ProfileCategoryAgent         = types.ProfileCategoryAgent
	ProfileCategorySourceControl = types.ProfileCategorySourceControl
	ProfileCategoryMessaging     = types.ProfileCategoryMessaging
	ProfileCategoryData          = types.ProfileCategoryData
	ProfileCategoryKnowledge     = types.ProfileCategoryKnowledge
)

ProfileCategory values.

View Source
const (
	RefreshStrategyStatic                  = types.RefreshStrategyStatic
	RefreshStrategyExternal                = types.RefreshStrategyExternal
	RefreshStrategyOAuth2RefreshToken      = types.RefreshStrategyOAuth2RefreshToken
	RefreshStrategyOAuth2ClientCredentials = types.RefreshStrategyOAuth2ClientCredentials
	RefreshStrategyGoogleServiceAccountJWT = types.RefreshStrategyGoogleServiceAccountJWT
)

RefreshStrategy values.

View Source
const (
	EndpointUnspecified           = types.EndpointUnspecified
	EndpointNoObservedExchange    = types.EndpointNoObservedExchange
	EndpointHTTPResponseReceived  = types.EndpointHTTPResponseReceived
	EndpointPolicyDenied          = types.EndpointPolicyDenied
	EndpointCredentialUnavailable = types.EndpointCredentialUnavailable
	EndpointTLSFailed             = types.EndpointTLSFailed
	EndpointTransportFailed       = types.EndpointTransportFailed
	EndpointUpstreamRejected      = types.EndpointUpstreamRejected
)

EndpointResult values describe passive observations of actual traffic.

View Source
const (
	// ServiceAuthorizationModeStrip removes Authorization before proxying to the service.
	ServiceAuthorizationModeStrip = types.ServiceAuthorizationModeStrip
	// ServiceAuthorizationModeBearerPassthrough forwards one valid bearer credential unchanged.
	ServiceAuthorizationModeBearerPassthrough = types.ServiceAuthorizationModeBearerPassthrough
)
View Source
const (
	SandboxProvisioning = types.SandboxProvisioning
	SandboxReady        = types.SandboxReady
	SandboxError        = types.SandboxError
	SandboxDeleting     = types.SandboxDeleting
	SandboxUnknown      = types.SandboxUnknown
	SandboxStopping     = types.SandboxStopping
	SandboxStopped      = types.SandboxStopped
	SandboxStarting     = types.SandboxStarting
	SandboxCompleted    = types.SandboxCompleted
)

SandboxPhase values for sandbox lifecycle.

View Source
const (
	SandboxRestartNever     = types.SandboxRestartNever
	SandboxRestartOnFailure = types.SandboxRestartOnFailure
	SandboxRestartAlways    = types.SandboxRestartAlways
)

Sandbox restart policy values.

View Source
const (
	EventAdded    = types.EventAdded
	EventModified = types.EventModified
	EventDeleted  = types.EventDeleted
	EventError    = types.EventError
)

EventType values for watch events.

View Source
const (
	StreamStdout = types.StreamStdout
	StreamStderr = types.StreamStderr
)

StreamType values for exec output.

View Source
const (
	// NetworkTLSModeUnspecified uses automatic TLS handling.
	NetworkTLSModeUnspecified = types.NetworkTLSModeUnspecified
	// NetworkTLSModeSkip disables TLS inspection.
	NetworkTLSModeSkip = types.NetworkTLSModeSkip
	// NetworkTLSModeTerminate is rejected by policy validation.
	NetworkTLSModeTerminate = types.NetworkTLSModeTerminate
	// NetworkTLSModePassthrough is rejected by policy validation.
	NetworkTLSModePassthrough = types.NetworkTLSModePassthrough

	// NetworkEnforcementModeUnspecified uses the documented audit default.
	NetworkEnforcementModeUnspecified = types.NetworkEnforcementModeUnspecified
	// NetworkEnforcementModeEnforce blocks policy violations.
	NetworkEnforcementModeEnforce = types.NetworkEnforcementModeEnforce
	// NetworkEnforcementModeAudit logs policy violations without blocking them.
	NetworkEnforcementModeAudit = types.NetworkEnforcementModeAudit

	// NetworkAccessPresetUnspecified selects no access preset.
	NetworkAccessPresetUnspecified = types.NetworkAccessPresetUnspecified
	// NetworkAccessPresetReadOnly permits read operations.
	NetworkAccessPresetReadOnly = types.NetworkAccessPresetReadOnly
	// NetworkAccessPresetReadWrite permits read and write operations.
	NetworkAccessPresetReadWrite = types.NetworkAccessPresetReadWrite
	// NetworkAccessPresetFull permits every operation supported by the protocol.
	NetworkAccessPresetFull = types.NetworkAccessPresetFull
)
View Source
const (
	WorkspaceActive      = types.WorkspaceActive
	WorkspaceTerminating = types.WorkspaceTerminating
	WorkspaceUnknown     = types.WorkspaceUnknown
)

WorkspacePhase constants.

View Source
const (
	WorkspaceRoleAdmin   = types.WorkspaceRoleAdmin
	WorkspaceRoleUser    = types.WorkspaceRoleUser
	WorkspaceRoleUnknown = types.WorkspaceRoleUnknown
)

WorkspaceRole constants.

Variables

View Source
var ErrTransportNotAvailable = errors.New("openshell: file transport not available")

ErrTransportNotAvailable indicates that this SDK build has no file-transfer transport. Callers can detect it with errors.Is.

View Source
var WithDraftApprovals = types.WithDraftApprovals

WithDraftApprovals supplies token-bound chunks for bulk approval.

View Source
var WithIncludeSecurityFlagged = types.WithIncludeSecurityFlagged

WithIncludeSecurityFlagged includes security-flagged chunks in bulk approval.

View Source
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.

View Source
var WithLogLines = types.WithLogLines

WithLogLines sets the maximum number of log lines to return.

View Source
var WithLogMinLevel = types.WithLogMinLevel

WithLogMinLevel sets the minimum log level to include.

View Source
var WithLogSince = types.WithLogSince

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

View Source
var WithLogSources = types.WithLogSources

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

View Source
var WithPageSize = types.WithPageSize

WithPageSize sets the maximum revisions requested per page.

View Source
var WithPageToken = types.WithPageToken

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

View Source
var WithStatusFilter = types.WithStatusFilter

WithStatusFilter filters draft chunks by approval status.

View Source
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.

View Source
var WithVersion = types.WithVersion

WithVersion queries a specific policy version instead of the latest.

Functions

func CancelInteractive

func CancelInteractive(session InteractiveSession) error

CancelInteractive aborts a session, falling back to the original Close contract.

func CloseInteractiveInput

func CloseInteractiveInput(session InteractiveSession) error

CloseInteractiveInput ends input while preserving output when supported. Unsupported sessions return ErrorUnimplemented and are left open.

func IsAlreadyExists

func IsAlreadyExists(err error) bool

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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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

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.

Example

ExampleIsNotFound demonstrates handling a not-found error.

package main

import (
	"context"
	"fmt"

	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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

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.

Example

ExampleIsUnavailable demonstrates detecting a closed client.

package main

import (
	"context"
	"fmt"

	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
)

func main() {
	client := fake.NewClient()
	_ = client.Close()

	ctx := context.Background()

	_, err := client.Sandboxes().Get(ctx, "default", "any")
	if v1.IsUnavailable(err) {
		fmt.Println("Client is closed")
	}
}
Output:
Client is closed

func IsUnimplemented

func IsUnimplemented(err error) bool

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 NoAuth

func NoAuth() AuthProvider

NoAuth returns an AuthProvider that sends no credentials.

func RefreshableToken

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 in-flight refresh via singleflight. Failed refreshes trigger exponential backoff (1s, 2s, 4s, ..., 30s cap) to avoid amplifying token endpoint outages.

func StaticToken

func StaticToken(token string) AuthProvider

StaticToken returns an AuthProvider that sends a fixed Bearer token.

func WithExtraHeaders

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

func NewClient(cfg Config) (*Client, error)

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/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
	"github.com/NVIDIA/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().ListAll(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/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
	"github.com/NVIDIA/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 (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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
	"github.com/NVIDIA/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) Close

func (c *Client) Close() error

Close closes the underlying gRPC connection. Safe to call multiple times.

func (*Client) Config

func (c *Client) Config() ConfigInterface

Config returns the configuration sub-client.

func (*Client) CreateSandboxFromTemplate

func (c *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error)

CreateSandboxFromTemplate creates a sandbox from a named workload template without changing the legacy Sandboxes() interface.

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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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) Files

func (c *Client) Files() FileInterface

Files returns the file sub-client.

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/NVIDIA/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) 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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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().ListAll(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) SSH

func (c *Client) SSH() SSHInterface

SSH returns the SSH session sub-client.

func (*Client) SandboxTemplates

func (c *Client) SandboxTemplates() SandboxTemplateInterface

SandboxTemplates returns the reusable sandbox template sub-client.

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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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. The returned handle accepts and tunnels connections internally.

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/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/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, dial ln.Addr() with the protocol client that should
		// connect to the sandbox service. No Accept loop is required.
		defer ln.Close() //nolint:errcheck
	}
}
Output:
Listen requires a real gateway

func (*Client) Workspaces

func (c *Client) Workspaces() WorkspaceInterface

Workspaces returns the workspace management sub-client.

type ClientInterface

type ClientInterface interface {
	Sandboxes() SandboxInterface
	SandboxTemplates() SandboxTemplateInterface
	CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error)
	Providers() ProviderInterface
	Services() ServiceInterface
	Exec() ExecInterface
	Files() FileInterface
	Health() HealthInterface
	SSH() SSHInterface
	TCP() TCPInterface
	Config() ConfigInterface
	Policy() PolicyInterface
	Workspaces() WorkspaceInterface
	Close() error
}

ClientInterface defines the top-level SDK surface.

type ComputeDriverInfo

type ComputeDriverInfo = types.ComputeDriverInfo

ComputeDriverInfo describes a compute backend available on the gateway.

type Config

type Config = types.Config

Config holds all settings needed to create a Client.

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

type CurrentUser = types.CurrentUser

CurrentUser holds the authenticated caller's identity.

type DeleteOptions

type DeleteOptions = types.DeleteOptions

DeleteOptions configures the missing-target contract.

type DeletionOutcome

type DeletionOutcome = types.DeletionOutcome

DeletionOutcome distinguishes completion from asynchronous acceptance.

type DeletionResult

type DeletionResult = types.DeletionResult

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

type DetachProviderResult

type DetachProviderResult = types.DetachProviderResult

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

type DraftChunkApproval

type DraftChunkApproval = types.DraftChunkApproval

DraftChunkApproval binds a bulk approval to an evaluated proposal.

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 EndpointResult

type EndpointResult = types.EndpointResult

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

type EndpointStatus

type EndpointStatus = types.EndpointStatus

EndpointStatus holds a configured tool endpoint and its last accepted network result.

type ErrorCode

type ErrorCode = types.ErrorCode

ErrorCode classifies SDK errors by their gRPC origin.

type ErrorInfo

type ErrorInfo = types.ErrorInfo

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

type Event

type Event[T any] = types.Event[T]

Event represents a watch event carrying a resource that changed.

type EventType

type EventType = types.EventType

EventType classifies watch events.

type ExecChunk

type ExecChunk = types.ExecChunk

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

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 ExecOptions

type ExecOptions = types.ExecOptions

ExecOptions configures command execution.

type ExecResult

type ExecResult = types.ExecResult

ExecResult holds the collected output of a completed command execution.

type ExecStream

type ExecStream interface {
	Next() (*ExecChunk, error)
	ExitCode() (int, error)
	Close() error
}

ExecStream provides an iterator interface over streaming command output.

type ExposeServiceOptions

type ExposeServiceOptions struct {
	AuthorizationMode ServiceAuthorizationMode
}

ExposeServiceOptions configures service exposure behavior.

type ExtensionInfo

type ExtensionInfo = types.ExtensionInfo

ExtensionInfo describes one successful gateway/extension negotiation.

type ExtensionKind

type ExtensionKind = types.ExtensionKind

ExtensionKind identifies one supported extension family.

type FieldViolation

type FieldViolation = types.FieldViolation

FieldViolation identifies an invalid request field.

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

type FilesystemPolicy = types.FilesystemPolicy

FilesystemPolicy controls which directories the sandbox can access.

type ForwardListener

type ForwardListener interface {
	Addr() net.Addr
	Close() error
}

ForwardListener is the lifecycle handle for a local TCP forward. The SDK owns accepting and bridging local connections; callers dial Addr and call Close when the forwarding endpoint is no longer needed.

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

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 InteractiveSession

type InteractiveSession interface {
	Read(p []byte) (int, error)
	Write(p []byte) (int, error)
	Resize(cols, rows uint32) error
	// ExitCode waits for final stream completion. An observed exit code is
	// returned alongside any later transport error. Drain Read concurrently.
	ExitCode() (int, error)
	Close() error
}

InteractiveSession provides bidirectional I/O for interactive command execution.

type InteractiveSessionControl

type InteractiveSessionControl interface {
	InteractiveSession
	// CloseWrite ends stdin and resize input without cancelling output.
	CloseWrite() error
	// Cancel aborts the RPC. Close retains the same full-close behavior.
	Cancel() error
}

InteractiveSessionControl adds optional input closure and cancellation to InteractiveSession without requiring existing implementations to add methods. Sessions returned by this SDK implement both interfaces.

type L7Allow

type L7Allow = types.L7Allow

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

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 L7Rule

type L7Rule = types.L7Rule

L7Rule wraps an L7 allow rule.

type L7RuleTarget

type L7RuleTarget = types.L7RuleTarget

L7RuleTarget identifies an endpoint and declares its complete affected scope.

type LandlockPolicy

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

type ListenOption func(*listenConfig)

ListenOption configures a local listener opened via TCPInterface.Listen.

func WithBindAddress

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

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

func WithSSHTunnel() ListenOption

WithSSHTunnel routes each accepted connection through an SSH tunnel (SSHInterface.Tunnel) instead of the default TCP forward (TCPInterface.Forward).

type LogLine

type LogLine = types.LogLine

LogLine represents a single log entry from a sandbox.

type LogOption

type LogOption = types.LogOption

LogOption configures a GetLogs call.

type LogResult

type LogResult = types.LogResult

LogResult contains the result of a GetLogs call.

type Logger

type Logger = types.Logger

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

type NetworkAccessPreset

type NetworkAccessPreset = types.NetworkAccessPreset

NetworkAccessPreset selects a predefined endpoint access policy.

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 NetworkEnforcementMode

type NetworkEnforcementMode = types.NetworkEnforcementMode

NetworkEnforcementMode controls endpoint L7 enforcement behavior.

type NetworkPolicyRule

type NetworkPolicyRule = types.NetworkPolicyRule

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

type NetworkTLSMode

type NetworkTLSMode = types.NetworkTLSMode

NetworkTLSMode controls TLS handling for a policy endpoint.

type Page

type Page[T any] struct {
	Items         []T
	NextPageToken string
}

Page is one response page from a list operation.

type Pager

type Pager[T any] struct {
	// contains filtered or unexported fields
}

Pager lazily fetches pages from the continuation-token contract.

A Pager is single-pass and must not be used concurrently. Its repeated-token guard has bounded memory and returns an error if the traversal exceeds its token-count or byte budget.

func NewPager

func NewPager[T any](pageToken string, fetch func(context.Context, string) (*Page[T], error)) *Pager[T]

NewPager constructs a pager from an RPC page fetcher.

func (*Pager[T]) All

func (p *Pager[T]) All(ctx context.Context) ([]T, error)

All consumes the pager and collects every remaining item.

func (*Pager[T]) NextPage

func (p *Pager[T]) NextPage(ctx context.Context) (*Page[T], error)

NextPage fetches the next page. It returns nil after the final page.

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, reviewToken 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(workspace, sandboxName string, opts ...ListPolicyOption) (*Pager[SandboxPolicyRevision], error)
	ListAll(ctx context.Context, workspace, sandboxName 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

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(workspace string, opts ...ListOptions) (*Pager[*ProviderProfile], error)
	ListAll(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, opts ...DeleteOptions) (*DeletionResult, error)
}

ProfileInterface defines operations for managing provider profiles.

type Provider

type Provider = types.Provider

Provider represents an AI provider registration.

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(workspace string, opts ...ListOptions) (*Pager[*Provider], error)
	ListAll(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, opts ...DeleteOptions) (*DeletionResult, 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, opts ...DeleteOptions) (*DeletionResult, error)
}

RefreshInterface defines operations for managing provider credential refresh.

type RefreshOption

type RefreshOption func(*refreshConfig)

RefreshOption configures the behavior of RefreshableToken.

func WithLeeway

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

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 SSHInterface

type SSHInterface interface {
	CreateSession(ctx context.Context, workspace, sandboxName string) (*SSHSession, error)
	RevokeSession(ctx context.Context, workspace, token string, opts ...DeleteOptions) (*DeletionResult, 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 Sandbox

type Sandbox = types.Sandbox

Sandbox represents a sandbox instance.

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 SandboxGPURequirements

type SandboxGPURequirements = types.SandboxGPURequirements

SandboxGPURequirements defines template GPU requirements.

type SandboxInterface

type SandboxInterface interface {
	Create(ctx context.Context, workspace, name string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error)
	Get(ctx context.Context, workspace, name string) (*Sandbox, error)
	List(workspace string, opts ...ListOptions) (*Pager[*Sandbox], error)
	ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error)
	Stop(ctx context.Context, workspace, name string) (*Sandbox, error)
	Start(ctx context.Context, workspace, name string) (*Sandbox, error)
	Delete(ctx context.Context, workspace, name string, opts ...DeleteOptions) (*DeletionResult, 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 returns a lazy pager over providers attached to a sandbox.
	ListProviders(workspace, sandboxName string, opts ...ListOptions) (*Pager[*Provider], error)
	// ListAllProviders exhausts ListProviders for callers that need every provider.
	ListAllProviders(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*Provider, error)
	WaitReady(ctx context.Context, workspace, name string, opts ...WaitOptions) (*Sandbox, error)
	WaitStopped(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

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 SandboxResources

type SandboxResources = types.SandboxResources

SandboxResources defines portable sandbox resource requirements.

type SandboxRestartPolicy

type SandboxRestartPolicy = types.SandboxRestartPolicy

SandboxRestartPolicy controls replacement after the canonical main process exits.

type SandboxServiceLevel

type SandboxServiceLevel = types.SandboxServiceLevel

SandboxServiceLevel describes desired operational characteristics.

type SandboxSpec

type SandboxSpec = types.SandboxSpec

SandboxSpec holds the desired state of a sandbox.

type SandboxStartup

type SandboxStartup = types.SandboxStartup

SandboxStartup describes desired startup characteristics.

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 SandboxTemplateCreateInterface

type SandboxTemplateCreateInterface interface {
	CreateFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error)
}

SandboxTemplateCreateInterface defines additive sandbox creation from named workload templates without widening SandboxInterface.

type SandboxTemplateInterface

type SandboxTemplateInterface interface {
	Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error)
	Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error)
	List(workspace string, opts ...ListOptions) (*Pager[*SandboxWorkloadTemplate], error)
	ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error)
	Delete(ctx context.Context, workspace, name string, opts ...DeleteOptions) (*DeletionResult, error)
}

SandboxTemplateInterface defines CRUD operations on reusable sandbox templates.

The resource type is named SandboxWorkloadTemplate in the v1 Go SDK so it does not collide with the legacy inline SandboxTemplate field on SandboxSpec.

type SandboxWorkloadConfig

type SandboxWorkloadConfig = types.SandboxWorkloadConfig

SandboxWorkloadConfig defines the portable workload for a reusable template.

type SandboxWorkloadTemplate

type SandboxWorkloadTemplate = types.SandboxWorkloadTemplate

SandboxWorkloadTemplate is a reusable workspace-scoped sandbox template resource.

type SandboxWorkloadTemplateProvenance

type SandboxWorkloadTemplateProvenance = types.SandboxWorkloadTemplateProvenance

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

type SandboxWorkloadTemplateSpec

type SandboxWorkloadTemplateSpec = types.SandboxWorkloadTemplateSpec

SandboxWorkloadTemplateSpec holds reusable sandbox template settings.

type ServiceAuthorizationMode

type ServiceAuthorizationMode = types.ServiceAuthorizationMode

ServiceAuthorizationMode controls handling of an incoming application Authorization header.

type ServiceEndpoint

type ServiceEndpoint = types.ServiceEndpoint

ServiceEndpoint represents an exposed HTTP service endpoint within a sandbox.

type ServiceExposure

type ServiceExposure = types.ServiceExposure

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

type ServiceInterface

type ServiceInterface interface {
	Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool, opts ...ExposeServiceOptions) (*ServiceEndpoint, error)
	Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error)
	List(workspace, sandboxName string, opts ...ListOptions) (*Pager[*ServiceEndpoint], error)
	ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error)
	Delete(ctx context.Context, workspace, sandboxName, serviceName string, opts ...DeleteOptions) (*DeletionResult, error)
}

ServiceInterface defines operations for managing sandbox service endpoints.

type ServiceStatus

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) (ForwardListener, error)
}

TCPInterface defines operations for TCP port forwarding to sandboxes. Methods accept a sandbox name and resolve it to an ID internally.

type TLSConfig

type TLSConfig = types.TLSConfig

TLSConfig holds TLS connection settings.

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 UpdateResult

type UpdateResult = types.UpdateResult

UpdateResult holds the result of a profile update operation.

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 WatchOptions

type WatchOptions = types.WatchOptions

WatchOptions configures watch behavior.

type Workspace

type Workspace = types.Workspace

Workspace represents a logical grouping of resources.

type WorkspaceInterface

type WorkspaceInterface interface {
	Create(ctx context.Context, name string, labels map[string]string) (*Workspace, error)
	Get(ctx context.Context, name string) (*Workspace, error)
	List(opts ...ListOptions) (*Pager[*Workspace], error)
	ListAll(ctx context.Context, opts ...ListOptions) ([]*Workspace, error)
	Delete(ctx context.Context, name string, opts ...DeleteOptions) (*DeletionResult, error)
	AddMember(ctx context.Context, workspace, principalSubject string, role WorkspaceRole) (*WorkspaceMember, error)
	RemoveMember(ctx context.Context, workspace, principalSubject string, opts ...DeleteOptions) (*DeletionResult, error)
	ListMembers(workspace string, opts ...ListOptions) (*Pager[*WorkspaceMember], error)
	ListAllMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error)
}

WorkspaceInterface defines workspace and member management operations.

type WorkspaceMember

type WorkspaceMember = types.WorkspaceMember

WorkspaceMember represents a user's membership in a workspace.

type WorkspacePhase

type WorkspacePhase = types.WorkspacePhase

WorkspacePhase describes the lifecycle state of a workspace.

type WorkspaceRole

type WorkspaceRole = types.WorkspaceRole

WorkspaceRole describes a member's role within a workspace.

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.
options
Package options provides a shared mechanism for applying functional options across all SDK entry points.
Package options provides a shared mechanism for applying functional options across all SDK entry points.
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.

Jump to

Keyboard shortcuts

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