sandbox

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// EnvAPIEndpoint overrides the default base URL when set.
	EnvAPIEndpoint = "TENKI_API_ENDPOINT"
	// EnvAPIURL overrides the default base URL when set.
	EnvAPIURL = "TENKI_API_URL"
	// EnvGatewayURL overrides the default gateway base URL when set.
	EnvGatewayURL = "TENKI_SANDBOX_GATEWAY_URL"
	// EnvAuthToken provides the auth token when not passed via WithAuthToken.
	EnvAuthToken = "TENKI_AUTH_TOKEN"
	// EnvAPIKey provides the auth token when not passed via WithAuthToken.
	EnvAPIKey = "TENKI_API_KEY"
)
View Source
const (
	DefaultSessionCreateTimeout      = 3 * time.Minute
	DefaultTemplateSpecCreateTimeout = 2 * time.Hour
	DefaultSnapshotCreateTimeout     = 5 * time.Minute
	DefaultRestoreTimeout            = 5 * time.Minute
	DefaultExecTimeout               = 30 * time.Second
	DefaultVolumeDetachTimeout       = 2 * time.Minute
)
View Source
const (
	SessionStateUnspecified  SessionState = "UNSPECIFIED"
	SessionStateCreating     SessionState = "CREATING"
	SessionStateRunning      SessionState = "RUNNING"
	SessionStatePaused       SessionState = "PAUSED"
	SessionStateUserShutdown SessionState = "USER_SHUTDOWN"
	SessionStatePausing      SessionState = "PAUSING"
	SessionStateResuming     SessionState = "RESUMING"
	SessionStateTerminating  SessionState = "TERMINATING"
	SessionStateTerminated   SessionState = "TERMINATED"

	RuntimeStateUnspecified RuntimeState = "UNSPECIFIED"
	RuntimeStateStarting    RuntimeState = "STARTING"
	RuntimeStateReady       RuntimeState = "READY"
	RuntimeStateFailed      RuntimeState = "FAILED"
	RuntimeStateStopped     RuntimeState = "STOPPED"
)
View Source
const (
	SnapshotStateUnspecified SnapshotState = "UNSPECIFIED"
	SnapshotStateCreating    SnapshotState = "CREATING"
	SnapshotStateReady       SnapshotState = "READY"
	SnapshotStateFailed      SnapshotState = "FAILED"
	SnapshotStateDeleting    SnapshotState = "DELETING"
	SnapshotStateDeleted     SnapshotState = "DELETED"

	SnapshotTypeUnspecified SnapshotType = "UNSPECIFIED"
	SnapshotTypeUser        SnapshotType = "USER"
	SnapshotTypePause       SnapshotType = "PAUSE"
	SnapshotTypeTemplate    SnapshotType = "TEMPLATE"

	SnapshotDurabilityStateUnspecified       SnapshotDurabilityState = "UNSPECIFIED"
	SnapshotDurabilityStateLocalReady        SnapshotDurabilityState = "LOCAL_READY"
	SnapshotDurabilityStateDurable           SnapshotDurabilityState = "DURABLE"
	SnapshotDurabilityStatePropagationFailed SnapshotDurabilityState = "PROPAGATION_FAILED"
	// DurableCeph means the snapshot is cluster-durable in Ceph (cross-node
	// usable on capability-matched hosts) but not yet uploaded to R2.
	SnapshotDurabilityStateDurableCeph SnapshotDurabilityState = "DURABLE_CEPH"
)
View Source
const (
	Byte int64 = 1

	KB int64 = 1000 * Byte
	MB int64 = 1000 * KB
	GB int64 = 1000 * MB
	TB int64 = 1000 * GB

	KiB int64 = 1024 * Byte
	MiB int64 = 1024 * KiB
	GiB int64 = 1024 * MiB
	TiB int64 = 1024 * GiB
)
View Source
const TemplateSpecVersion = "tenki.template.v1"

TemplateSpecVersion is the canonical template build spec version emitted by this SDK.

Variables

View Source
var (
	ErrSessionNotFound         = errors.New("sandbox: session not found")
	ErrSessionExpired          = errors.New("sandbox: session expired")
	ErrSessionTerminated       = errors.New("sandbox: session terminated")
	ErrFileNotFound            = errors.New("sandbox: file not found")
	ErrInvalidState            = errors.New("sandbox: invalid session state for operation")
	ErrCommandTimeout          = errors.New("sandbox: command execution timed out")
	ErrUnauthorized            = errors.New("sandbox: unauthorized")
	ErrPermissionDenied        = errors.New("sandbox: permission denied")
	ErrQuotaExceeded           = errors.New("sandbox: quota exceeded")
	ErrCapacityUnavailable     = errors.New("sandbox: capacity unavailable, please retry")
	ErrPortLimitExceeded       = errors.New("sandbox: maximum exposed ports reached")
	ErrInboundDisabled         = errors.New("sandbox: inbound access is disabled")
	ErrSSHUnavailable          = errors.New("sandbox: ssh unavailable")
	ErrRateLimited             = errors.New("sandbox: rate limited")
	ErrVolumeNotFound          = errors.New("sandbox: volume not found")
	ErrVolumeInUse             = errors.New("sandbox: volume is attached to a session")
	ErrVolumeSyncPending       = errors.New("sandbox: volume sync back is still pending")
	ErrVolumeLimitExceeded     = errors.New("sandbox: volume limit exceeded")
	ErrGitOperationFailed      = errors.New("sandbox: git operation failed")
	ErrStreamClosed            = errors.New("sandbox: interactive stream closed")
	ErrInvalidResourceConfig   = errors.New("sandbox: invalid resource configuration")
	ErrSnapshotNotFound        = errors.New("sandbox: snapshot not found")
	ErrSnapshotFailed          = errors.New("sandbox: snapshot failed")
	ErrResumeFailed            = errors.New("sandbox: resume failed")
	ErrSnapshotNotDurable      = errors.New("sandbox: snapshot upload did not become durable")
	ErrTemplateNotFound        = errors.New("sandbox: template not found")
	ErrRegistryImageNotFound   = errors.New("sandbox: registry image not found")
	ErrTemplateExists          = errors.New("sandbox: template already exists")
	ErrTemplateBuildNotFound   = errors.New("sandbox: template build not found")
	ErrTemplateBuildFailed     = errors.New("sandbox: template build failed")
	ErrTemplateBuildInProgress = errors.New("sandbox: template build already in progress")
	ErrTemplateRuntimeFailed   = errors.New("sandbox: template runtime failed")
	ErrPaginationStalled       = errors.New("sandbox: pagination token did not advance")
)

Pure SDK errors

View Source
var ErrMissingAuthToken = errors.New("sandbox: missing auth token - set TENKI_AUTH_TOKEN or TENKI_API_KEY or use WithAuthToken")

ErrMissingAuthToken is returned when no auth token is provided via WithAuthToken or env vars.

View Source
var ErrTemplateSpecInvalid = errors.New("sandbox: template spec invalid")

ErrTemplateSpecInvalid is the sentinel wrapped by TemplateSpecValidationError.

Functions

func IsCapabilityUnavailable

func IsCapabilityUnavailable(err error) bool

IsCapabilityUnavailable reports whether err means the server/image lacks a requested primitive. Matches both authoritative CapabilityUnavailableError and the watchdog-emitted PrimitiveTimeoutError so existing fallback paths keep working; callers that want to discriminate use IsPrimitiveTimeout.

func IsDataPlaneNotReady

func IsDataPlaneNotReady(err error) bool

func IsGitOperationFailed

func IsGitOperationFailed(err error) bool

func IsPrimitiveTimeout

func IsPrimitiveTimeout(err error) bool

func WithEnvs

func WithEnvs(env map[string]string) interface {
	CreateOption
	ExecOption
	TemplateOption
}

WithEnvs sets environment variables for Create (session defaults) or Exec (command overrides).

func WithName

WithName sets a human-readable name on create and update requests.

func WithTags

WithTags sets session or template tags on create/update requests.

func WithWorkspaceID

func WithWorkspaceID(workspaceID string) interface {
	CreateOption
	CreateVolumeOption
	TemplateOption
	ListOption
	PreviewURLOption
}

WithWorkspaceID explicitly scopes requests for trusted service credentials. Workspace API keys infer their scope automatically.

Types

type CapabilityUnavailableError

type CapabilityUnavailableError struct {
	Primitive string
	Message   string
}

func (*CapabilityUnavailableError) Error

type CheckoutMode added in v0.4.0

type CheckoutMode string

CheckoutMode selects how Git repository contents land in the guest.

const (
	CheckoutModeContents  CheckoutMode = "contents"
	CheckoutModeDirectory CheckoutMode = "directory"
)

type Client

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

Client is an idiomatic wrapper over SandboxService Connect client.

func New

func New(opts ...Option) (*Client, error)

New creates a new sandbox SDK client.

Auth token resolution: WithAuthToken option > TENKI_AUTH_TOKEN env var > TENKI_API_KEY env var > error. Base URL resolution: WithBaseURL option > TENKI_API_ENDPOINT env var > TENKI_API_URL env var > https://api.tenki.cloud. Gateway URL resolution: WithGatewayAddress option > TENKI_SANDBOX_GATEWAY_URL env var > derived from base URL.

func (*Client) BindPreviewURL

func (c *Client) BindPreviewURL(ctx context.Context, previewURLID string, sessionID string, port int32) (*PreviewURL, error)

func (*Client) BuildTemplate

func (c *Client) BuildTemplate(ctx context.Context, template any, opts ...TemplateBuildOption) (*TemplateBuild, error)

BuildTemplate starts one template build. It accepts a *Template resource object or a raw template ID string.

func (*Client) CancelTemplateBuild added in v0.4.0

func (c *Client) CancelTemplateBuild(ctx context.Context, build any) (*TemplateBuild, error)

CancelTemplateBuild explicitly cancels one remote build (*TemplateBuild or ID string) and returns the terminal build.

func (*Client) Close

func (c *Client) Close() error

Close closes idle HTTP connections held by the underlying transport.

func (*Client) Create

func (c *Client) Create(ctx context.Context, opts ...CreateOption) (*Session, error)

Create creates a sandbox session and returns an SDK Session wrapper.

func (*Client) CreateAndWait

func (c *Client) CreateAndWait(ctx context.Context, timeout time.Duration, opts ...CreateOption) (*Session, error)

CreateAndWait is kept for compatibility: Create already waits by default. It is equivalent to Create with WithWaitTimeout(timeout).

func (*Client) CreatePreviewURL

func (c *Client) CreatePreviewURL(ctx context.Context, slug string, sessionID *string, port *int32, opts ...PreviewURLOption) (*PreviewURL, error)

CreatePreviewURL creates a sticky preview URL owned by the Workspace API key.

func (*Client) CreateSnapshot

func (c *Client) CreateSnapshot(ctx context.Context, sessionID, name string, expiresAt *time.Time) (*Snapshot, error)

CreateSnapshot creates a snapshot for one session.

func (*Client) CreateSnapshotAndWait

func (c *Client) CreateSnapshotAndWait(ctx context.Context, sessionID, name string, expiresAt *time.Time, timeout time.Duration) (*Snapshot, error)

CreateSnapshotAndWait creates a snapshot and waits for it to reach READY state.

func (*Client) CreateSnapshotAsync added in v0.4.0

func (c *Client) CreateSnapshotAsync(ctx context.Context, sessionID, name string, expiresAt *time.Time) (*Snapshot, error)

CreateSnapshotAsync creates a snapshot and returns as soon as the snapshot is accepted.

func (*Client) CreateTemplate

func (c *Client) CreateTemplate(ctx context.Context, opts ...TemplateOption) (*Template, error)

CreateTemplate creates one sandbox template.

func (*Client) CreateVolume

func (c *Client) CreateVolume(ctx context.Context, opts ...CreateVolumeOption) (*Volume, error)

CreateVolume creates a workspace-scoped persistent volume.

func (*Client) DeletePreviewURL

func (c *Client) DeletePreviewURL(ctx context.Context, previewURLID string) error

func (*Client) DeleteRegistryImage

func (c *Client) DeleteRegistryImage(ctx context.Context, imageOrID, reason string) (*RegistryDeleteResult, error)

func (*Client) DeleteRegistryImageVersion added in v0.4.0

func (c *Client) DeleteRegistryImageVersion(ctx context.Context, imageID, snapshotID string) (*RegistryVersionDeleteResult, error)

func (*Client) DeleteSnapshot

func (c *Client) DeleteSnapshot(ctx context.Context, snapshotID string) (*Snapshot, error)

DeleteSnapshot deletes one snapshot.

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, template any) (*Template, error)

DeleteTemplate deletes one template (*Template or ID string). Built images and tags stay launchable until deleted from the registry.

func (*Client) DeleteVolume

func (c *Client) DeleteVolume(ctx context.Context, volumeID string) error

DeleteVolume soft-deletes one persistent volume. Retries up to 60 s when the volume has a sync-pending attachment (node-agent still uploading).

func (*Client) DiscoverSSHGateway

func (c *Client) DiscoverSSHGateway(ctx context.Context, sessionID string) string

DiscoverSSHGateway calls engine.ListActiveSSHGateways and returns the per-session WS URL built from the first healthy gateway's ws_bridge_endpoint. Returns "" when the engine has nothing to announce (older engines, no gateways configured, or the call fails) so SSH() falls back to its derived default.

CLI callers use the result to share one discovery response between cert minting and the ssh-proxy process.

func (*Client) Get

func (c *Client) Get(ctx context.Context, sessionID string) (*Session, error)

Get fetches a single session by ID.

func (*Client) GetPreviewURL

func (c *Client) GetPreviewURL(ctx context.Context, previewURLID string) (*PreviewURL, error)

func (*Client) GetRegistryImage

func (c *Client) GetRegistryImage(
	ctx context.Context,
	imageOrID string,
	opts ...RegistryLookupOption,
) (*RegistryImageDetail, error)

func (*Client) GetSnapshot

func (c *Client) GetSnapshot(ctx context.Context, snapshotID string) (*Snapshot, error)

GetSnapshot fetches one snapshot by ID.

func (*Client) GetSnapshotDownloadURL

func (c *Client) GetSnapshotDownloadURL(ctx context.Context, snapshotID string) (*SnapshotDownloadURL, error)

GetSnapshotDownloadURL returns a short-lived download URL for a template snapshot's raw image.

func (*Client) GetTemplate

func (c *Client) GetTemplate(ctx context.Context, template any) (*Template, error)

GetTemplate fetches one template (*Template or ID string).

func (*Client) GetTemplateBuild

func (c *Client) GetTemplateBuild(ctx context.Context, build any) (*TemplateBuild, error)

GetTemplateBuild fetches one template build (*TemplateBuild or ID string).

func (*Client) GetVolume

func (c *Client) GetVolume(ctx context.Context, volumeID string) (*Volume, error)

GetVolume fetches a single persistent volume by ID.

func (*Client) IssueSandboxSSHCert

func (c *Client) IssueSandboxSSHCert(ctx context.Context, sessionID, publicKey string, ttl time.Duration) (*SSHCert, error)

IssueSandboxSSHCert asks the engine to sign an SSH user cert for the given session. publicKey is OpenSSH-format (e.g. "ssh-ed25519 AAAA..."). ttl caps the cert validity (server clamps to policy max; pass 0 for the server default).

Use the returned SSHCert.SSHCert as the `CertificateFile` for OpenSSH, or write it to disk alongside the private key as `<key>-cert.pub` so ssh auto-loads it.

func (*Client) List

func (c *Client) List(ctx context.Context, opts ...ListOption) ([]*Session, error)

List lists sessions owned by the Workspace API key.

func (*Client) ListActiveTemplateBuilds added in v0.4.0

func (c *Client) ListActiveTemplateBuilds(ctx context.Context, template any) ([]*TemplateBuild, error)

ListActiveTemplateBuilds lists pending/building executions for a template (*Template or ID string), newest template-local build number first.

func (*Client) ListDanglingSnapshots

func (c *Client) ListDanglingSnapshots(ctx context.Context) ([]*Snapshot, error)

ListDanglingSnapshots lists snapshots whose source session is gone or terminating.

func (*Client) ListPreviewURLs

func (c *Client) ListPreviewURLs(ctx context.Context, opts ...PreviewURLOption) ([]*PreviewURL, error)

ListPreviewURLs lists sticky preview URLs owned by the Workspace API key.

func (*Client) ListRegistryImages

func (c *Client) ListRegistryImages(ctx context.Context, opts ...RegistryListOption) (*RegistryListResult, error)

func (*Client) ListRegistryShareGrants

func (c *Client) ListRegistryShareGrants(ctx context.Context, imageOrID string) ([]*RegistryShareGrant, error)

func (*Client) ListSessionSnapshots

func (c *Client) ListSessionSnapshots(ctx context.Context, sessionID string) ([]*Snapshot, error)

ListSessionSnapshots lists snapshots created from one session.

func (*Client) ListSnapshots

func (c *Client) ListSnapshots(ctx context.Context, opts ...ListOption) ([]*Snapshot, error)

ListSnapshots lists snapshots owned by the Workspace API key.

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context, opts ...ListOption) ([]*Template, error)

ListTemplates lists templates owned by the Workspace API key.

func (*Client) ListVolumes

func (c *Client) ListVolumes(ctx context.Context, opts ...ListOption) ([]*Volume, error)

ListVolumes lists persistent volumes owned by the Workspace API key.

func (*Client) PublishRegistryImage

func (c *Client) PublishRegistryImage(ctx context.Context, opts ...RegistryPublishOption) (*RegistryPublishResult, error)

func (*Client) ResizeVolume

func (c *Client) ResizeVolume(ctx context.Context, volumeID string, newSizeBytes int64) (*Volume, error)

ResizeVolume updates one persistent volume's size.

func (*Client) ResolveRegistryRef

func (c *Client) ResolveRegistryRef(
	ctx context.Context,
	image string,
	opts ...RegistryLookupOption,
) (*ResolvedRegistryRef, error)

func (*Client) RevokeRegistryShareGrant

func (c *Client) RevokeRegistryShareGrant(ctx context.Context, grantID, reason string) (*RegistryShareGrant, error)

func (*Client) SSH

func (c *Client) SSH(ctx context.Context, sessionID string, opts ...SSHOption) (*SSHConn, error)

SSH opens an SSH transport to the given session ID via the gateway WebSocket.

func (*Client) Session

func (c *Client) Session(sessionID string) (*Session, error)

Session returns a local session handle for an already-known session ID without an API lookup.

func (*Client) ShareImage

func (c *Client) ShareImage(ctx context.Context, imageOrID string, targetWorkspaceID string, opts ...RegistryShareOption) (*RegistryShareResult, error)

func (*Client) UnbindPreviewURL

func (c *Client) UnbindPreviewURL(ctx context.Context, previewURLID string) (*PreviewURL, error)

func (*Client) UnpublishRegistryImage

func (c *Client) UnpublishRegistryImage(ctx context.Context, imageOrID string) (*RegistryImage, error)

func (*Client) UnshareRegistryImage

func (c *Client) UnshareRegistryImage(ctx context.Context, imageOrID, reason string) (*RegistryUnshareResult, error)

func (*Client) UpdateSnapshot

func (c *Client) UpdateSnapshot(ctx context.Context, snapshotID string, opts ...UpdateSnapshotOption) (*Snapshot, error)

UpdateSnapshot applies mutable snapshot fields.

func (*Client) UpdateTemplate

func (c *Client) UpdateTemplate(ctx context.Context, template any, opts ...TemplateOption) (*Template, error)

UpdateTemplate updates one template (*Template or ID string). Metadata is patchable; a typed spec passed via WithTemplateSpec replaces the whole spec atomically.

func (*Client) UpdateVolume

func (c *Client) UpdateVolume(ctx context.Context, volumeID string, opts ...UpdateVolumeOption) (*Volume, error)

UpdateVolume applies mutable volume fields.

func (*Client) WaitForSnapshotDurable

func (c *Client) WaitForSnapshotDurable(ctx context.Context, snapshotID string) (*Snapshot, error)

WaitForSnapshotDurable polls until the snapshot's R2 upload is complete. Returns the snapshot when DurabilityState == DURABLE, ErrSnapshotFailed when the snapshot itself failed, or ErrSnapshotNotDurable when durability ended at PROPAGATION_FAILED.

func (*Client) WaitForTemplateBuild

func (c *Client) WaitForTemplateBuild(ctx context.Context, build any) (*TemplateBuild, error)

WaitForTemplateBuild polls a build (*TemplateBuild or ID string) until READY or FAILED; context cancellation stops local observation only, never the remote build.

func (*Client) WaitForTemplateBuildWithEvents added in v0.4.0

func (c *Client) WaitForTemplateBuildWithEvents(ctx context.Context, build any, handler TemplateBuildEventHandler) (*TemplateBuild, error)

WaitForTemplateBuildWithEvents observes ordered events while waiting. It reconnects to an existing build, replaying events in order exactly once.

func (*Client) WaitSnapshotReady

func (c *Client) WaitSnapshotReady(ctx context.Context, snapshotID string, timeout time.Duration) (*Snapshot, error)

WaitSnapshotReady polls until a snapshot reaches READY or a terminal state.

func (*Client) WaitVolumeReady

func (c *Client) WaitVolumeReady(ctx context.Context, volumeID string, timeout time.Duration) (*Volume, error)

WaitVolumeReady polls until a volume reaches AVAILABLE or a terminal state.

func (*Client) WhoAmI

func (c *Client) WhoAmI(ctx context.Context) (*Identity, error)

WhoAmI returns the authenticated caller's identity.

type Command

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

func (*Command) Exec

func (c *Command) Exec(ctx context.Context) (*Result, error)

func (*Command) Stream

func (c *Command) Stream(ctx context.Context) (*RunHandle, error)

type CommandStatus

type CommandStatus string

CommandStatus represents command execution status.

const (
	CommandStatusUnspecified CommandStatus = "UNSPECIFIED"
	CommandStatusQueued      CommandStatus = "QUEUED"
	CommandStatusRunning     CommandStatus = "RUNNING"
	CommandStatusSucceeded   CommandStatus = "SUCCEEDED"
	CommandStatusFailed      CommandStatus = "FAILED"
	CommandStatusTimedOut    CommandStatus = "TIMED_OUT"
)

func (CommandStatus) IsFailed

func (s CommandStatus) IsFailed() bool

IsFailed returns true if the command failed.

func (CommandStatus) IsSuccess

func (s CommandStatus) IsSuccess() bool

IsSuccess returns true if the command succeeded.

func (CommandStatus) IsTimedOut

func (s CommandStatus) IsTimedOut() bool

IsTimedOut returns true if the command timed out.

type CreateOption

type CreateOption interface {
	// contains filtered or unexported methods
}

CreateOption configures Create behavior.

func FromTemplateSpec added in v0.5.0

func FromTemplateSpec[T TemplateSpecSource](template T) CreateOption

FromTemplateSpec executes the current typed template spec directly in the new session.

func WithAllowInbound

func WithAllowInbound(allowInbound bool) CreateOption

WithAllowInbound sets inbound network policy on Create requests.

func WithAllowOutbound

func WithAllowOutbound(allowOutbound bool) CreateOption

WithAllowOutbound sets outbound network policy on Create requests.

func WithCPUCores

func WithCPUCores(cpuCores int32) CreateOption

WithCPUCores sets CPU cores on Create requests.

func WithCloneRepo

func WithCloneRepo(repoURL string) CreateOption

WithCloneRepo configures repo clone during provisioning and enables opencode.

func WithDiskSizeGB

func WithDiskSizeGB(gb int) CreateOption

WithDiskSizeGB sets ephemeral root disk size on Create requests.

func WithGitHubToken

func WithGitHubToken(token string) CreateOption

WithGitHubToken sets both GH_TOKEN and GIT_TOKEN for Create.

func WithIdleTimeout

func WithIdleTimeout(idleTimeout time.Duration) CreateOption

WithIdleTimeout sets the inactivity window after which a session is auto-paused.

func WithImage

func WithImage[T ImageSource](image T) CreateOption

WithImage launches a new session from a registry image. A *RegistryImage uses its immutable digest ref when present, else its untagged ref.

func WithMaxDuration

func WithMaxDuration(maxDuration time.Duration) CreateOption

WithMaxDuration sets max session duration on Create requests.

func WithMemoryMB

func WithMemoryMB(memoryMB int32) CreateOption

WithMemoryMB sets memory on Create requests.

func WithMetadata

func WithMetadata(metadata map[string]string) CreateOption

WithMetadata sets metadata on Create requests.

func WithOpenCode

func WithOpenCode(enabled bool) CreateOption

WithOpenCode toggles eager opencode startup during session provisioning.

func WithOpenCodeProvider

func WithOpenCodeProvider(provider OpenCodeProviderConfig) CreateOption

WithOpenCodeProvider sets OpenCode provider env vars for Create.

func WithPauseRetention

func WithPauseRetention(retention time.Duration) CreateOption

WithPauseRetention sets how long paused state is retained for the session.

func WithSSHKeys

func WithSSHKeys(keys []string) CreateOption

WithSSHKeys overrides session SSH authorized keys at creation time.

func WithSetupEnvs added in v0.5.0

func WithSetupEnvs(env map[string]string) CreateOption

WithSetupEnvs sets non-secret environment variables used only by template setup.

func WithSetupSecrets added in v0.5.0

func WithSetupSecrets(secrets map[string]string) CreateOption

WithSetupSecrets sets secret environment variables used only by template setup.

func WithSnapshot

func WithSnapshot(snapshotID string) CreateOption

WithSnapshot restores a new session from one snapshot instead of cold-booting from a base image.

func WithSticky

func WithSticky() CreateOption

WithSticky marks a session as sticky on Create.

func WithVolume

func WithVolume(volumeID, mountPath string, opts ...VolumeOption) CreateOption

WithVolume attaches a persistent volume during Create.

func WithWaitForRuntime added in v0.4.0

func WithWaitForRuntime(wait bool) CreateOption

WithWaitForRuntime holds Create until an image boot runtime is READY or FAILED.

func WithWaitReady

func WithWaitReady(wait bool) CreateOption

WithWaitReady controls whether Create waits for the session to be RUNNING and exec-ready before returning (default true); pass false to return immediately in CREATING.

func WithWaitTimeout

func WithWaitTimeout(timeout time.Duration) CreateOption

WithWaitTimeout overrides the readiness wait (default 2h for direct template specs, otherwise 3m).

type CreateVolumeOption

type CreateVolumeOption interface {
	// contains filtered or unexported methods
}

CreateVolumeOption configures volume creation behavior.

func WithVolumeName

func WithVolumeName(name string) CreateVolumeOption

WithVolumeName sets the volume name for CreateVolume.

func WithVolumeSize

func WithVolumeSize(sizeBytes int64) CreateVolumeOption

WithVolumeSize sets the volume size in bytes for CreateVolume. Prefer helpers like GB or GiB.

type DataPlaneNotReadyError

type DataPlaneNotReadyError struct {
	Message  string
	Err      error
	Terminal bool
}

func (*DataPlaneNotReadyError) Error

func (e *DataPlaneNotReadyError) Error() string

func (*DataPlaneNotReadyError) IsRetryable

func (e *DataPlaneNotReadyError) IsRetryable() bool

func (*DataPlaneNotReadyError) Unwrap

func (e *DataPlaneNotReadyError) Unwrap() error

type DetachVolumeOption

type DetachVolumeOption interface {
	// contains filtered or unexported methods
}

DetachVolumeOption configures Session.DetachVolume behavior.

func WithDetachWaitTimeout

func WithDetachWaitTimeout(timeout time.Duration) DetachVolumeOption

WithDetachWaitTimeout overrides how long Session.DetachVolume waits for the attachment to leave the session. RW volumes may transition to `SYNC_PENDING` before later becoming `DETACHED` once sync-back completes. Use `0` to return immediately after the detach RPC succeeds.

func WithForceDetach

func WithForceDetach() DetachVolumeOption

WithForceDetach bypasses stuck SYNC_PENDING cleanup and marks the attachment detached immediately.

type DialOptions

type DialOptions struct {
	ConnectTimeout time.Duration
}

type ExecCheckOptions added in v0.4.0

type ExecCheckOptions struct {
	Timeout time.Duration
}

ExecCheckOptions configures one exec readiness check.

type ExecOption

type ExecOption interface {
	// contains filtered or unexported methods
}

ExecOption configures Exec behavior.

func WithArgs

func WithArgs(args ...string) ExecOption

WithArgs sets command args for Exec.

func WithDir added in v0.4.0

func WithDir(dir string) ExecOption

WithDir sets the command working directory. Relative paths resolve under the sandbox guest workdir; absolute paths are used unchanged.

func WithEnv

func WithEnv(key, value string) ExecOption

WithEnv sets a single command environment override.

func WithOnOutput

func WithOnOutput(fn func(Output)) ExecOption

WithOnOutput sets a callback invoked for each output chunk during Exec. The callback fires as chunks arrive from the server stream, before Exec returns. The full Result is still returned with aggregated Stdout/Stderr.

func WithTimeout

func WithTimeout(timeout time.Duration) ExecOption

WithTimeout sets timeout for Exec.

type ExposePortOption

type ExposePortOption interface {
	// contains filtered or unexported methods
}

ExposePortOption configures Session.ExposePort behavior.

func WithExposureTTL

func WithExposureTTL(ttl time.Duration) ExposePortOption

WithExposureTTL sets a relative TTL for one exposed port.

func WithSlug

func WithSlug(slug string) ExposePortOption

type ExposedPort

type ExposedPort struct {
	Port         int32
	PreviewURL   string
	ExpiresAt    *time.Time
	PreviewURLID string
	Slug         string
}

type FileInfo

type FileInfo struct {
	Path           string
	Size           int64
	Mode           uint32
	IsDir          bool
	ModifiedUnixNs int64
	IsSymlink      bool
	SymlinkTarget  string
}

type Git

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

Git is a scoped helper for structured git operations on one session.

func (*Git) Checkout

func (g *Git) Checkout(ctx context.Context, ref string, params GitCheckoutParams) (string, error)

Checkout executes git checkout with structured params.

func (*Git) Clone

func (g *Git) Clone(ctx context.Context, repo string, params GitCloneParams) (string, error)

Clone executes git clone with structured params.

func (*Git) Diff

func (g *Git) Diff(ctx context.Context, params GitDiffParams) (string, error)

Diff executes git diff with structured params.

func (*Git) FetchPR

func (g *Git) FetchPR(ctx context.Context, prNumber int, params GitFetchPRParams) (string, error)

FetchPR fetches pull/<number>/head into a local branch and checks it out.

func (*Git) Log

func (g *Git) Log(ctx context.Context, params GitLogParams) (string, error)

Log executes git log with structured params.

type GitCheckoutParams

type GitCheckoutParams struct {
	Create bool
}

GitCheckoutParams controls checkout behavior.

type GitCloneParams

type GitCloneParams struct {
	Branch    string
	Depth     int
	Directory string
}

GitCloneParams controls clone behavior.

type GitContext added in v0.4.0

type GitContext struct {
	Repo string
	Ref  string
	// CheckoutDest is the optional absolute checkout destination (defaults to the spec workdir).
	CheckoutDest string
	CheckoutMode CheckoutMode
	// CheckoutName names the child directory in directory mode.
	CheckoutName string
	Ignore       []string
}

GitContext is the backend-fetched Git build context. Copy step sources are relative to this checkout; no local upload or archive transport exists.

type GitDiffParams

type GitDiffParams struct {
	Range string
	Base  string
	Head  string
	Path  string
}

GitDiffParams controls diff behavior.

type GitFetchPRParams

type GitFetchPRParams struct {
	Directory    string
	Remote       string
	BranchPrefix string
}

GitFetchPRParams controls fetch+checkout behavior for pull requests.

type GitLogParams

type GitLogParams struct {
	MaxCount int
	Range    string
	Path     string
}

GitLogParams controls log behavior.

type GitOperation

type GitOperation string

GitOperation is the structured git operation name.

const (
	GitClone    GitOperation = "clone"
	GitCheckout GitOperation = "checkout"
	GitDiff     GitOperation = "diff"
	GitLog      GitOperation = "log"
)

type GitOperationFailedError

type GitOperationFailedError struct {
	Message   string
	Stderr    string
	ExitCode  *int
	Retryable bool
	Err       error
}

GitOperationFailedError classifies an in-guest git failure surfaced by node-agent as FailedPrecondition.

func (*GitOperationFailedError) Error

func (e *GitOperationFailedError) Error() string

func (*GitOperationFailedError) IsRetryable

func (e *GitOperationFailedError) IsRetryable() bool

func (*GitOperationFailedError) Unwrap

func (e *GitOperationFailedError) Unwrap() error

type HostPortTunnel

type HostPortTunnel struct {
	SandboxPort    uint32
	SandboxAddress string
	// contains filtered or unexported fields
}

func (*HostPortTunnel) Close

func (t *HostPortTunnel) Close() error

func (*HostPortTunnel) OnTerminated

func (t *HostPortTunnel) OnTerminated(cb func(HostPortTunnelTermination))

func (*HostPortTunnel) Terminated

func (t *HostPortTunnel) Terminated() <-chan HostPortTunnelTermination

type HostPortTunnelOptions

type HostPortTunnelOptions struct {
	SandboxBindAddress  string
	SandboxPort         uint32
	HostDialTargetLabel string
}

type HostPortTunnelTermination

type HostPortTunnelTermination struct {
	Reason TunnelTerminationReason
	Detail string
	Err    error
}

type Identity

type Identity struct {
	OwnerType  string
	OwnerID    string
	Workspaces []IdentityWorkspace
}

Identity represents the authenticated caller's identity.

type IdentityWorkspace

type IdentityWorkspace struct {
	ID   string
	Name string
}

IdentityWorkspace is a workspace returned by WhoAmI.

type ImageSource added in v0.4.0

type ImageSource interface {
	string | *RegistryImage
}

ImageSource is a sandbox launch image: a raw registry ref string or a *RegistryImage resource object (for example a successful build's Image).

type ListOption

type ListOption interface {
	// contains filtered or unexported methods
}

ListOption configures list filtering behavior.

func WithStickyFilter

func WithStickyFilter(sticky bool) ListOption

WithStickyFilter filters sessions by sticky flag on List.

func WithTagFilter

func WithTagFilter(tags ...string) ListOption

WithTagFilter sets AND-tag filtering on list requests.

type ListOptions

type ListOptions struct {
	IncludeHidden bool
}

type MkdirOptions added in v0.4.0

type MkdirOptions struct {
	Name    string
	Parents bool
	Mode    fs.FileMode
}

MkdirOptions configures one mkdir step.

type OpenCodeProviderConfig

type OpenCodeProviderConfig struct {
	APIKey  string
	BaseURL string
	Npm     string
}

OpenCodeProviderConfig configures OpenCode provider env vars for Create.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures Client behavior.

func WithAuthToken

func WithAuthToken(token string) Option

WithAuthToken sets the API authentication token.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets sandbox service base URL.

func WithConnectClientOptions

func WithConnectClientOptions(opts ...connect.ClientOption) Option

WithConnectClientOptions appends connect client options.

func WithCookieName

func WithCookieName(name string) Option

WithCookieName overrides the default session cookie name ("tenki_session").

func WithDataPlaneReadyTimeout

func WithDataPlaneReadyTimeout(timeout time.Duration) Option

WithDataPlaneReadyTimeout sets the wall-clock budget used to wait for the data-plane edge route to become serving.

func WithGatewayAddress

func WithGatewayAddress(addr string) Option

WithGatewayAddress sets the sandbox gateway base URL used for SSH websocket transport.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets custom HTTP client.

func WithHTTPTimeout

func WithHTTPTimeout(timeout time.Duration) Option

WithHTTPTimeout sets HTTP timeout for default HTTP client.

type Output

type Output struct {
	Data     []byte
	IsStderr bool
	IsFinal  bool
}

Output is a stream chunk emitted by data-plane Run.

type PreviewURL

type PreviewURL struct {
	ID             string
	WorkspaceID    string
	OwnerID        string
	Slug           string
	Token          string
	PreviewURL     string
	SessionID      string
	Port           *int32
	CreatedAt      time.Time
	UpdatedAt      time.Time
	LastAccessedAt *time.Time
}

type PreviewURLOption added in v0.5.0

type PreviewURLOption interface {
	// contains filtered or unexported methods
}

PreviewURLOption configures preview URL create and list behavior.

type PrimitiveTimeoutError

type PrimitiveTimeoutError struct {
	Primitive string
	Message   string
}

func (*PrimitiveTimeoutError) Error

func (e *PrimitiveTimeoutError) Error() string

type ProcessComposeOptions added in v0.4.0

type ProcessComposeOptions struct {
	Workdir       string
	EnvFiles      []string
	RunAt         RunAt
	RestartPolicy TemplateRestartPolicy
}

ProcessComposeOptions configures a process-compose runtime entrypoint.

type ReadyCheck added in v0.4.0

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

ReadyCheck is one readiness probe; build with ReadyPort, ReadyHTTP, ReadyExec, or ReadyExecArgs.

func ReadyExec added in v0.4.0

func ReadyExec(command string, opts ...ExecCheckOptions) ReadyCheck

ReadyExec waits for a shell command to exit zero.

func ReadyExecArgs added in v0.4.0

func ReadyExecArgs(argv []string, opts ...ExecCheckOptions) ReadyCheck

ReadyExecArgs waits for an argv-form command to exit zero.

func ReadyHTTP added in v0.4.0

func ReadyHTTP(url string, successStatusCodes ...int) ReadyCheck

ReadyHTTP waits for a localhost HTTP endpoint to return a success status (2xx by default).

func ReadyPort added in v0.4.0

func ReadyPort(port int) ReadyCheck

ReadyPort waits for a guest TCP port to accept connections.

type ReadyWhen added in v0.4.0

type ReadyWhen struct {
	// Timeout bounds readiness polling; defaults to 60s when checks are set.
	Timeout time.Duration
	// PollInterval defaults server-side to 1s when zero.
	PollInterval time.Duration
	Checks       []ReadyCheck
}

ReadyWhen is the runtime readiness contract shared by build, boot, manual start, and cold-fallback recovery.

type RegistryDeleteResult

type RegistryDeleteResult struct {
	Image             *RegistryImage
	RevokedTokenCount int32
	RevokedGrantCount int32
}

type RegistryImage

type RegistryImage struct {
	ID                     string
	WorkspaceID            string
	WorkspaceSlug          string
	Name                   string
	Kind                   RegistryImageKind
	Visibility             RegistryVisibility
	Title                  string
	Description            string
	Labels                 []string
	SourceTemplateID       string
	SourceSnapshotID       string
	Tags                   []*RegistryTag
	CreatedAt              time.Time
	UpdatedAt              time.Time
	ChangesNotYetPublished bool
	// Digest and DigestRef pin the exact built output when the image came from
	// a template build (for example "sha256:..." and "acme/api@sha256:...").
	Digest    string
	DigestRef string
}

func (*RegistryImage) Ref added in v0.4.0

func (i *RegistryImage) Ref() string

Ref returns the untagged image ref that resolves the latest eligible build.

type RegistryImageDetail

type RegistryImageDetail struct {
	Image              *RegistryImage
	ResolvedSnapshotID string
	ResolvedRef        string
	WorkspaceActive    bool
	Tombstoned         bool
	MaskedEnvVarKeys   []string
	Metadata           map[string]string
	EnvVars            map[string]string
}

type RegistryImageKind

type RegistryImageKind string
const (
	RegistryImageKindTemplate RegistryImageKind = "template"
	RegistryImageKindSnapshot RegistryImageKind = "snapshot"
)

type RegistryImageSummary

type RegistryImageSummary struct {
	ID                     string
	WorkspaceID            string
	WorkspaceSlug          string
	Name                   string
	Kind                   RegistryImageKind
	Visibility             RegistryVisibility
	Labels                 []string
	Tags                   []*RegistryTag
	LatestSnapshotID       string
	LatestRef              string
	UpdatedAt              time.Time
	ChangesNotYetPublished bool
}

type RegistryListOption

type RegistryListOption func(*sandboxv1.ListRegistryImagesRequest)

func WithRegistryCursor

func WithRegistryCursor(cursor string) RegistryListOption

func WithRegistryKind

func WithRegistryKind(kind RegistryImageKind) RegistryListOption

func WithRegistryLabels

func WithRegistryLabels(labels ...string) RegistryListOption

func WithRegistryNameSubstring

func WithRegistryNameSubstring(name string) RegistryListOption

func WithRegistryPageSize

func WithRegistryPageSize(size int32) RegistryListOption

func WithRegistrySort

func WithRegistrySort(sortBy RegistrySortBy) RegistryListOption

func WithRegistryWorkspace

func WithRegistryWorkspace(slug string) RegistryListOption

func WithRegistryWorkspaceID

func WithRegistryWorkspaceID(workspaceID string) RegistryListOption

type RegistryListResult

type RegistryListResult struct {
	Images     []*RegistryImageSummary
	NextCursor string
}

type RegistryLookupOption added in v0.4.0

type RegistryLookupOption func(*registryLookupOptions)

func WithRegistryLookupWorkspaceID added in v0.4.0

func WithRegistryLookupWorkspaceID(workspaceID string) RegistryLookupOption

type RegistryPublishOption

type RegistryPublishOption func(*sandboxv1.PublishRegistryImageRequest)

func WithRegistryDescription

func WithRegistryDescription(description string) RegistryPublishOption

func WithRegistryImage

func WithRegistryImage(image string) RegistryPublishOption

func WithRegistryPublishLabels

func WithRegistryPublishLabels(labels ...string) RegistryPublishOption

func WithRegistrySnapshot

func WithRegistrySnapshot(snapshotID string) RegistryPublishOption

func WithRegistryTag

func WithRegistryTag(tag string) RegistryPublishOption

func WithRegistryTemplate

func WithRegistryTemplate(templateID string) RegistryPublishOption

func WithRegistryTitle

func WithRegistryTitle(title string) RegistryPublishOption

func WithRegistryVisibility

func WithRegistryVisibility(visibility RegistryVisibility) RegistryPublishOption

func WithRegistryWorkspaceName

func WithRegistryWorkspaceName(workspaceID string, name string) RegistryPublishOption

type RegistryPublishResult

type RegistryPublishResult struct {
	Image      *RegistryImage
	Tag        *RegistryTag
	SnapshotID string
	DigestRef  string
}

type RegistryShareGrant

type RegistryShareGrant struct {
	ID                string
	ImageID           string
	OwnerWorkspaceID  string
	TargetWorkspaceID string
	CurrentSnapshotID string
	GrantedViaTokenID string
	AcceptedBy        string
	AcceptedAt        time.Time
	RevokedAt         time.Time
	FollowMode        string
	FollowTag         string
}

type RegistryShareOption

type RegistryShareOption func(*sandboxv1.ShareImageRequest)

func WithRegistryShareSnapshotID

func WithRegistryShareSnapshotID(snapshotID string) RegistryShareOption

func WithRegistryShareTag

func WithRegistryShareTag(tag string) RegistryShareOption

type RegistryShareResult

type RegistryShareResult struct {
	Image             *RegistryImage
	CurrentSnapshotID string
	DigestRef         string
	Grant             *RegistryShareGrant
}

type RegistrySortBy

type RegistrySortBy string
const (
	RegistrySortUpdatedAt RegistrySortBy = "updated_at"
	RegistrySortName      RegistrySortBy = "name"
)

type RegistryTag

type RegistryTag struct {
	ID         string
	ImageID    string
	Tag        string
	SnapshotID string
	Ref        string
	UpdatedAt  time.Time
}

type RegistryUnshareResult

type RegistryUnshareResult struct {
	Image             *RegistryImage
	RevokedTokenCount int32
	RevokedGrantCount int32
}

type RegistryVersionDeleteResult added in v0.4.0

type RegistryVersionDeleteResult struct {
	ImageID    string
	SnapshotID string
}

type RegistryVisibility

type RegistryVisibility string
const (
	RegistryVisibilityPrivate RegistryVisibility = "private"
	RegistryVisibilityPublic  RegistryVisibility = "public"
	RegistryVisibilityShared  RegistryVisibility = "shared"
)

type RemoveOptions added in v0.4.0

type RemoveOptions struct {
	Name      string
	Recursive bool
}

RemoveOptions configures one remove step.

type ResilientHostPortTunnel

type ResilientHostPortTunnel struct {
	SandboxPort    uint32
	SandboxAddress string
	// contains filtered or unexported fields
}

func (*ResilientHostPortTunnel) Close

func (t *ResilientHostPortTunnel) Close() error

func (*ResilientHostPortTunnel) OnStateChange

func (*ResilientHostPortTunnel) OnTerminated

func (t *ResilientHostPortTunnel) OnTerminated(cb func(HostPortTunnelTermination))

func (*ResilientHostPortTunnel) State

func (*ResilientHostPortTunnel) Terminated

func (t *ResilientHostPortTunnel) Terminated() <-chan HostPortTunnelTermination

type ResilientHostPortTunnelOptions

type ResilientHostPortTunnelOptions struct {
	HostPortTunnelOptions
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

type ResilientHostPortTunnelState

type ResilientHostPortTunnelState string
const (
	ResilientHostPortTunnelStateOpen         ResilientHostPortTunnelState = "open"
	ResilientHostPortTunnelStateReconnecting ResilientHostPortTunnelState = "reconnecting"
	ResilientHostPortTunnelStateClosed       ResilientHostPortTunnelState = "closed"
)

type ResilientHostPortTunnelStateEvent

type ResilientHostPortTunnelStateEvent struct {
	State        string
	Reason       HostPortTunnelTermination
	Attempt      int
	Delay        time.Duration
	PreviousPort uint32
	SandboxPort  uint32
}

type ResolvedRegistryRef

type ResolvedRegistryRef struct {
	ImageID             string
	OwningWorkspaceID   string
	OwningWorkspaceSlug string
	ImageName           string
	SnapshotID          string
	ResolvedRef         string
	Kind                RegistryImageKind
	Visibility          RegistryVisibility
}

type Result

type Result struct {
	SessionID string
	Command   string
	Args      []string
	Status    CommandStatus
	ExitCode  int32
	Duration  time.Duration
	StartedAt *time.Time
	EndedAt   *time.Time
	Outputs   []Output
	Stdout    []byte
	Stderr    []byte
}

Result is the normalized command execution result.

func (*Result) StderrString

func (r *Result) StderrString() string

StderrString returns trimmed stderr as a string.

func (*Result) StdoutString

func (r *Result) StdoutString() string

StdoutString returns trimmed stdout as a string.

type RunAt added in v0.4.0

type RunAt string

RunAt selects when the declared runtime starts.

const (
	RunAtBoot   RunAt = "boot"
	RunAtBuild  RunAt = "build"
	RunAtManual RunAt = "manual"
)

type RunHandle

type RunHandle struct {
	PID    uint64
	Stdin  io.WriteCloser
	Stdout io.Reader
	Stderr io.Reader
	// contains filtered or unexported fields
}

func (*RunHandle) Kill

func (h *RunHandle) Kill() error

func (*RunHandle) Signal

func (h *RunHandle) Signal(signal os.Signal) error

func (*RunHandle) Wait

func (h *RunHandle) Wait() (*Result, error)

type RunOptions

type RunOptions struct {
	Env        map[string]string
	Dir        string
	Stdin      io.Reader
	Timeout    *time.Duration
	Privileged bool
}

type RunStepOptions added in v0.4.0

type RunStepOptions struct {
	Name    string
	Workdir string
	Timeout time.Duration
}

RunStepOptions configures one run step.

type RuntimeState added in v0.4.0

type RuntimeState string

type SSHCert

type SSHCert struct {
	SSHCert    string
	CAPub      string
	ExpiresAt  time.Time
	CertSerial string
}

SSHCert is the result of IssueSandboxSSHCert. SSHCert is the OpenSSH cert in authorized_keys format (begins with "ssh-ed25519-cert-v01@openssh.com"). CAPub is the user-CA public key for known_hosts pinning. ExpiresAt is when the cert stops being valid (gateway rejects after this).

type SSHConn

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

func (*SSHConn) Close

func (c *SSHConn) Close() error

func (*SSHConn) CloseWrite

func (c *SSHConn) CloseWrite() error

func (*SSHConn) Read

func (c *SSHConn) Read(p []byte) (int, error)

func (*SSHConn) Write

func (c *SSHConn) Write(p []byte) (int, error)

type SSHOption

type SSHOption func(*sshOptions)

SSHOption configures a single SSH() call.

func WithGatewayURL

func WithGatewayURL(u string) SSHOption

WithGatewayURL overrides the gateway WebSocket URL for this SSH call. Format: "ws://host:port", "wss://host:port", "http://host:port", or "https://host:port" (http/https are normalized to ws/wss). The path/query of the SDK's computed URL is preserved; only scheme+host are replaced.

When unset, falls back to the SDK client's configured gateway URL. Use to point the SSH connection at a specific edge gateway:

client.SSH(ctx, sid, sandbox.WithGatewayURL("wss://gateway.example.com:2222"))

type Session

type Session struct {
	Git *Git

	ID                        string
	Name                      string
	State                     SessionState
	OwnerType                 string
	OwnerID                   string
	WorkspaceID               string
	InboundEnabled            bool
	OutboundEnabled           bool
	CPUCores                  int32
	MemoryMB                  int32
	DiskSizeGB                int32
	TimeoutAt                 time.Time
	IdleTimeoutMinutes        *int32
	LastActivityAt            time.Time
	PausedAt                  time.Time
	PauseSnapshotID           string
	PauseRetention            *time.Duration
	PauseExpiresAt            *time.Time
	Sticky                    bool
	Metadata                  map[string]string
	Tags                      []string
	VolumeMounts              []VolumeMount
	PauseSnapshot             *Snapshot
	LastResumeError           string
	TerminalError             string
	RuntimeState              RuntimeState
	RuntimeError              string
	SourceRegistryImageID     string
	SourceSnapshotID          string
	SourceRegistryWorkspaceID string
	SourceRegistryRef         string
	SourceTemplateID          string
	// contains filtered or unexported fields
}

Session is SDK view of sandbox session.

func (*Session) AttachVolume

func (s *Session) AttachVolume(ctx context.Context, volumeID string, mountPath string, opts ...VolumeOption) error

AttachVolume hot-attaches one persistent volume to the running session.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close terminates this session.

func (*Session) CloseIfOpen

func (s *Session) CloseIfOpen(ctx context.Context) error

CloseIfOpen terminates the session if it is not already terminated. Safe to call multiple times.

func (*Session) Command

func (s *Session) Command(argv []string, opts ...RunOptions) *Command

func (*Session) DetachVolume

func (s *Session) DetachVolume(ctx context.Context, volumeID string, opts ...DetachVolumeOption) error

DetachVolume detaches one persistent volume from the session.

func (*Session) Dial

func (s *Session) Dial(ctx context.Context, unixSocketPath string, opts ...DialOptions) (net.Conn, error)

func (*Session) Exec deprecated

func (s *Session) Exec(ctx context.Context, command string, opts ...ExecOption) (*Result, error)

Exec executes one command, waits for completion, and returns collected output. For incremental consumption, use Stream.

Deprecated: use Session.Command(...).Exec instead.

func (*Session) ExposeHostPort

func (s *Session) ExposeHostPort(ctx context.Context, hostAddr string, opts ...HostPortTunnelOptions) (*HostPortTunnel, error)

func (*Session) ExposeHostPortResilient

func (s *Session) ExposeHostPortResilient(ctx context.Context, hostAddr string, opts ...ResilientHostPortTunnelOptions) (*ResilientHostPortTunnel, error)

func (*Session) ExposePort

func (s *Session) ExposePort(ctx context.Context, port int32, opts ...ExposePortOption) (*ExposedPort, error)

ExposePort publishes a guest port through the preview gateway.

func (*Session) Extend

func (s *Session) Extend(ctx context.Context, additional time.Duration) error

Extend extends this session timeout by additional duration.

func (*Session) GitOperation

func (s *Session) GitOperation(ctx context.Context, operation GitOperation, args map[string]string) (string, error)

GitOperation runs one structured git operation inside a sandbox session. Deprecated: prefer session.Git.Clone/Checkout/Diff/Log for better ergonomics.

func (*Session) HostPortTunnel

func (s *Session) HostPortTunnel(ctx context.Context, host string, port int, opts ...HostPortTunnelOptions) (*HostPortTunnel, error)

HostPortTunnel is kept for the phase-2 skeleton API; prefer ExposeHostPort.

func (*Session) List

func (s *Session) List(ctx context.Context, path string, opts ...ListOptions) ([]FileInfo, error)

func (*Session) ListExposedPorts

func (s *Session) ListExposedPorts(ctx context.Context) ([]ExposedPort, error)

ListExposedPorts returns all exposed ports for this session.

func (*Session) Mkdir

func (s *Session) Mkdir(ctx context.Context, path string) error

func (*Session) Pause

func (s *Session) Pause(ctx context.Context) error

Pause suspends this session and refreshes local session state from the response.

func (*Session) ReadFile

func (s *Session) ReadFile(ctx context.Context, path string) ([]byte, error)

ReadFile reads file content from inside the session.

func (*Session) ReadFileStream

func (s *Session) ReadFileStream(ctx context.Context, path string) (io.ReadCloser, error)

func (*Session) ReadStream

func (s *Session) ReadStream(ctx context.Context, path string, offset, length int64) (io.ReadCloser, error)

func (*Session) Refresh

func (s *Session) Refresh(ctx context.Context) error

Refresh re-fetches session state from the server.

func (*Session) Remove

func (s *Session) Remove(ctx context.Context, path string) error

func (*Session) ResilientHostPortTunnel

func (s *Session) ResilientHostPortTunnel(ctx context.Context, host string, port int, opts ...ResilientHostPortTunnelOptions) (*ResilientHostPortTunnel, error)

func (*Session) Resume

func (s *Session) Resume(ctx context.Context) error

Resume resumes a paused session and refreshes local session state from the response.

func (*Session) SSH

func (s *Session) SSH(ctx context.Context, opts ...SSHOption) (*SSHConn, error)

SSH opens an SSH transport to the session via the gateway WebSocket.

func (*Session) Stat

func (s *Session) Stat(ctx context.Context, path string) (*FileInfo, error)

func (*Session) Stream deprecated

func (s *Session) Stream(ctx context.Context, command string, opts ...ExecOption) (*Stream, error)

Stream starts a command immediately and returns incremental stdout/stderr output. Completion is reported separately through Wait. Stream rejects WithOnOutput; callers should consume chunks with Next instead.

Deprecated: use Session.Command(...).Stream instead.

func (*Session) UnexposePort

func (s *Session) UnexposePort(ctx context.Context, port int32) error

UnexposePort removes one preview port mapping.

func (*Session) Update

func (s *Session) Update(ctx context.Context, opts ...UpdateSessionOption) error

Update applies mutable session fields.

func (*Session) UpdateSSHAuthorizedKeys

func (s *Session) UpdateSSHAuthorizedKeys(ctx context.Context, keys []string) error

UpdateSSHAuthorizedKeys replaces authorized SSH keys for this session.

func (*Session) UpdateTags

func (s *Session) UpdateTags(ctx context.Context, tags ...string) error

UpdateTags replaces tags for this session.

func (*Session) WaitReady

func (s *Session) WaitReady(ctx context.Context, timeout time.Duration) error

WaitReady waits until the session reaches RUNNING or a terminal state.

func (*Session) WaitResumed added in v0.5.0

func (s *Session) WaitResumed(ctx context.Context, timeout time.Duration) error

WaitResumed waits until an in-flight resume reaches RUNNING or fails. Unlike WaitReady — which only treats TERMINATED/TERMINATING as terminal and would spin until timeout — a session that reverts from RESUMING back to a stopped state (PAUSED/USER_SHUTDOWN) returns ErrResumeFailed carrying the server-side last_resume_error.

func (*Session) WriteFile

func (s *Session) WriteFile(ctx context.Context, path string, data []byte) error

WriteFile writes content into a file inside the session.

func (*Session) WriteFileStream

func (s *Session) WriteFileStream(ctx context.Context, path string, r io.Reader) error

WriteFileStream needs no TS-style early-abort/buffering guard: Write sends synchronously, so an early server reject stops io.Copy at the next Send.

func (*Session) WriteStream

func (s *Session) WriteStream(ctx context.Context, path string, opts ...WriteStreamOptions) (io.WriteCloser, error)

type SessionState

type SessionState string

SessionState mirrors session lifecycle states from service contract.

func (SessionState) IsReady

func (s SessionState) IsReady() bool

IsReady returns true if the session can accept commands.

func (SessionState) IsTerminal

func (s SessionState) IsTerminal() bool

IsTerminal returns true if the session has reached a final state.

type Snapshot

type Snapshot struct {
	ID              string
	SessionID       string
	WorkspaceID     string
	Name            string
	State           SnapshotState
	SizeBytes       int64
	CompressedBytes int64
	MemoryBytes     int64
	BaseImageID     string
	CreatedAt       time.Time
	ExpiresAt       time.Time
	Tags            []string
	Type            SnapshotType
	CPUCores        int32
	MemoryMB        int32
	DiskSizeGB      int32
	// FailureReason is populated when State is FAILED; empty otherwise.
	FailureReason string
	// DurabilityState reports whether the snapshot bytes have been uploaded to R2.
	// LOCAL_READY means the snapshot exists on its origin host's disk but is not yet durable.
	// DURABLE means R2 holds a copy and the snapshot can restore on any host.
	DurabilityState SnapshotDurabilityState
	// PropagationError is the last durability-propagation error (e.g. a failed
	// R2 upload). It may be set without demoting DurabilityState for a
	// cluster-durable (DURABLE_CEPH) snapshot, so callers can distinguish a
	// stalled R2 upload from a snapshot that is still progressing.
	PropagationError string
	// RawImageAvailable is true when the snapshot has a standalone compressed
	// rootfs disk image artifact.
	RawImageAvailable bool
}

Snapshot is the SDK view of a sandbox snapshot.

type SnapshotDownloadURL

type SnapshotDownloadURL struct {
	URL       string
	ExpiresAt time.Time
}

SnapshotDownloadURL is a short-lived object-store URL for one snapshot file.

type SnapshotDurabilityState

type SnapshotDurabilityState string

SnapshotDurabilityState mirrors snapshot R2-upload durability from the service contract.

func (SnapshotDurabilityState) IsDurable

func (s SnapshotDurabilityState) IsDurable() bool

IsDurable returns true if the snapshot's R2 upload is complete.

type SnapshotMode added in v0.4.0

type SnapshotMode string

SnapshotMode selects what a build-time runtime snapshot captures.

const (
	SnapshotModeFilesystem SnapshotMode = "filesystem"
	SnapshotModeMemory     SnapshotMode = "memory"
)

type SnapshotState

type SnapshotState string

SnapshotState mirrors snapshot lifecycle states from the service contract.

func (SnapshotState) IsReady

func (s SnapshotState) IsReady() bool

IsReady returns true if the snapshot is usable for restore.

func (SnapshotState) IsTerminal

func (s SnapshotState) IsTerminal() bool

IsTerminal returns true if the snapshot has reached a final state.

type SnapshotType

type SnapshotType string

type StartOptions added in v0.4.0

type StartOptions struct {
	Workdir       string
	RunAt         RunAt
	RestartPolicy TemplateRestartPolicy
	// ReadyWhen sets readiness checks with a default 60s timeout; use the
	// ReadyWhen builder method for full control.
	ReadyWhen []ReadyCheck
}

StartOptions configures a single-command runtime entrypoint.

type StepOptions added in v0.4.0

type StepOptions struct {
	Name string
}

StepOptions configures steps that only support a display name.

type Stream

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

Stream yields incremental command output and a separate terminal result. Chunks are delivered through Next; terminal command status comes from Wait.

func (*Stream) Cancel

func (s *Stream) Cancel()

Cancel stops local stream consumption. It does not guarantee remote command termination and Wait will subsequently return the local cancellation error.

func (*Stream) Next

func (s *Stream) Next() (Output, error)

Next returns the next stdout/stderr chunk. It returns io.EOF once the stream has been drained. If Wait already drained unread chunks, Next may reach EOF earlier than the remote command's natural output boundary.

func (*Stream) Wait

func (s *Stream) Wait() (*Result, error)

Wait blocks until the command reaches a terminal state. It may drain and discard unread chunks so callers do not need to fully consume Next to get the final result. Multiple Wait calls return the same cached result.

type Template

type Template struct {
	ID                string
	WorkspaceID       string
	OwnerType         string
	OwnerID           string
	Name              string
	BaseImageID       string
	SetupScript       string
	StartCmd          string
	EnvVars           map[string]string
	Tags              []string
	Resources         *TemplateResources
	LatestBuild       *TemplateBuild
	Visibility        TemplateVisibility
	DefinitionMode    TemplateDefinitionMode
	ParentWorkspaceID string
	// Spec is the normalized build spec for both legacy and typed templates;
	// SpecHash is its server-computed canonical hash.
	Spec      *TemplateSpec
	SpecHash  string
	CreatedAt time.Time
	UpdatedAt time.Time
}

Template is the SDK view of one sandbox template.

type TemplateBuild

type TemplateBuild struct {
	ID                 string
	TemplateID         string
	State              TemplateBuildState
	Version            int32
	Error              string
	BuildLogTail       string
	BuildLogTruncated  bool
	BuildLogArtifactID string
	StartedAt          time.Time
	CompletedAt        time.Time
	SnapshotID         string
	SessionID          string
	// Spec is the immutable normalized spec frozen at submission; SpecHash is
	// its server-computed canonical hash.
	Spec     *TemplateSpec
	SpecHash string
	// Image is the private registry image registered by a successful build;
	// ImageDigest/ImageDigestRef pin the exact built output.
	Image          *RegistryImage
	ImageDigest    string
	ImageDigestRef string
	Events         []TemplateBuildEvent
	Provenance     *TemplateBuildProvenance
	Failure        *TemplateBuildFailure
}

TemplateBuild is the SDK view of one template build.

type TemplateBuildEvent added in v0.4.0

type TemplateBuildEvent struct {
	Log      *TemplateBuildLogEvent
	Progress *TemplateBuildProgressEvent
}

type TemplateBuildEventHandler added in v0.4.0

type TemplateBuildEventHandler func(TemplateBuildEvent) error

type TemplateBuildFailedError added in v0.4.0

type TemplateBuildFailedError struct {
	Build *TemplateBuild
}

func (*TemplateBuildFailedError) Error added in v0.4.0

func (e *TemplateBuildFailedError) Error() string

func (*TemplateBuildFailedError) Unwrap added in v0.4.0

func (e *TemplateBuildFailedError) Unwrap() error

type TemplateBuildFailure added in v0.4.0

type TemplateBuildFailure struct {
	Code    string
	Message string
	Step    *TemplateBuildStepReference
}

type TemplateBuildLogEvent added in v0.4.0

type TemplateBuildLogEvent struct {
	Timestamp time.Time
	Phase     string
	Step      *TemplateBuildStepReference
	Stream    string
	Data      string
}

type TemplateBuildOption

type TemplateBuildOption interface {
	// contains filtered or unexported methods
}

TemplateBuildOption configures one template build.

func WithBuildEnv added in v0.4.0

func WithBuildEnv(env map[string]string) TemplateBuildOption

WithBuildEnv provides request-scoped environment overrides frozen into this build without mutating the template.

func WithBuildEventHandler added in v0.4.0

func WithBuildEventHandler(handler TemplateBuildEventHandler) TemplateBuildOption

WithBuildEventHandler observes ordered build events while waiting.

func WithBuildPublishRawImage

func WithBuildPublishRawImage(publish bool) TemplateBuildOption

WithBuildPublishRawImage overrides whether this build publishes the raw rootfs disk image alongside the build snapshot. Unset defers to server configuration.

func WithBuildSecrets added in v0.4.0

func WithBuildSecrets(secrets map[string]string) TemplateBuildOption

WithBuildSecrets provides ephemeral environment variables to a template build. Values are not persisted on the template or build record.

func WithWaitForCompletion added in v0.4.0

func WithWaitForCompletion(wait bool) TemplateBuildOption

WithWaitForCompletion makes BuildTemplate wait for a terminal build.

type TemplateBuildProgressEvent added in v0.4.0

type TemplateBuildProgressEvent struct {
	Timestamp time.Time
	Phase     string
	Step      *TemplateBuildStepReference
	State     string
	Message   string
}

type TemplateBuildProvenance added in v0.4.0

type TemplateBuildProvenance struct {
	RequestedGitRef      string
	ResolvedGitCommitSHA string
	BuildSecretKeys      []string
}

type TemplateBuildState

type TemplateBuildState string

TemplateBuildState mirrors template build lifecycle states from the service contract.

const (
	TemplateBuildStateUnspecified TemplateBuildState = "UNSPECIFIED"
	TemplateBuildStatePending     TemplateBuildState = "PENDING"
	TemplateBuildStateBuilding    TemplateBuildState = "BUILDING"
	TemplateBuildStateReady       TemplateBuildState = "READY"
	TemplateBuildStateFailed      TemplateBuildState = "FAILED"
)

func (TemplateBuildState) IsReady

func (s TemplateBuildState) IsReady() bool

IsReady returns true if the build snapshot is ready for restore.

func (TemplateBuildState) IsTerminal

func (s TemplateBuildState) IsTerminal() bool

IsTerminal returns true if the build has reached a final state.

type TemplateBuildStepReference added in v0.4.0

type TemplateBuildStepReference struct {
	Index int32
	Kind  string
	Name  string
	Label string
}

type TemplateDefinitionMode added in v0.4.0

type TemplateDefinitionMode string

TemplateDefinitionMode identifies how a template definition is stored.

const (
	TemplateDefinitionModeUnspecified TemplateDefinitionMode = "UNSPECIFIED"
	TemplateDefinitionModeLegacy      TemplateDefinitionMode = "LEGACY"
	TemplateDefinitionModeTyped       TemplateDefinitionMode = "TYPED"
)

type TemplateOption

type TemplateOption interface {
	// contains filtered or unexported methods
}

TemplateOption configures template create/update behavior.

func WithBaseImageID

func WithBaseImageID(baseImageID string) TemplateOption

WithBaseImageID sets the template base image.

func WithParentImage

func WithParentImage(image string) TemplateOption

WithParentImage builds a template on top of a pinned registry image snapshot.

func WithParentTemplateID

func WithParentTemplateID(templateID string) TemplateOption

WithParentTemplateID builds a template on top of the current publication of another template.

func WithSetupScript

func WithSetupScript(script string) TemplateOption

WithSetupScript sets the template setup script for CreateTemplate/UpdateTemplate.

func WithStartCmd

func WithStartCmd(startCmd string) TemplateOption

WithStartCmd sets the template start command for CreateTemplate/UpdateTemplate.

func WithTemplateDiskSizeGB

func WithTemplateDiskSizeGB(gb int32) TemplateOption

WithTemplateDiskSizeGB sets the template default ephemeral root disk size.

func WithTemplateName

func WithTemplateName(name string) TemplateOption

WithTemplateName sets the template name for CreateTemplate/UpdateTemplate.

func WithTemplateResources

func WithTemplateResources(cpuCores, memoryMB int32) TemplateOption

WithTemplateResources sets template CPU and memory defaults in MB.

func WithTemplateSpec added in v0.4.0

func WithTemplateSpec(spec TemplateSpec) TemplateOption

WithTemplateSpec sets the typed build spec for CreateTemplate/UpdateTemplate. It cannot be combined with legacy field options; updates replace the spec atomically.

type TemplateResources

type TemplateResources struct {
	CPUCores   int32
	MemoryMB   int32
	DiskSizeGB int32
}

TemplateResources is the SDK view of template CPU/memory defaults.

type TemplateRestartPolicy added in v0.4.0

type TemplateRestartPolicy string

TemplateRestartPolicy selects boot/manual runtime restart behavior.

const (
	RestartNever     TemplateRestartPolicy = "never"
	RestartOnFailure TemplateRestartPolicy = "on-failure"
	RestartAlways    TemplateRestartPolicy = "always"
)

type TemplateRuntimeFailedError added in v0.4.0

type TemplateRuntimeFailedError struct {
	Session *Session
	Reason  string
	Err     error
}

func (*TemplateRuntimeFailedError) Error added in v0.4.0

func (*TemplateRuntimeFailedError) Is added in v0.4.0

func (e *TemplateRuntimeFailedError) Is(target error) bool

func (*TemplateRuntimeFailedError) Unwrap added in v0.4.0

func (e *TemplateRuntimeFailedError) Unwrap() error

type TemplateSpec added in v0.4.0

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

TemplateSpec is an immutable typed template build recipe: every fluent method returns a new value, methods never panic, and Validate reports all violations.

func NewTemplateSpec added in v0.4.0

func NewTemplateSpec() TemplateSpec

NewTemplateSpec returns a spec builder on the default Tenki base image "sandbox".

func TemplateSpecFromJSON added in v0.4.0

func TemplateSpecFromJSON(data []byte) (TemplateSpec, error)

TemplateSpecFromJSON accepts short or protobuf enum names and rejects unknown fields. The parsed spec still goes through Validate on submission.

func (TemplateSpec) Apt added in v0.4.0

func (s TemplateSpec) Apt(packages ...string) TemplateSpec

Apt appends an apt package install step.

func (TemplateSpec) BuildEnv added in v0.4.0

func (s TemplateSpec) BuildEnv(env map[string]string) TemplateSpec

BuildEnv merges persisted build-time environment variables.

func (TemplateSpec) Bun added in v0.4.0

func (s TemplateSpec) Bun(packages ...string) TemplateSpec

Bun appends a bun package install step.

func (TemplateSpec) Copy added in v0.4.0

func (s TemplateSpec) Copy(src, dest string, opts ...StepOptions) TemplateSpec

Copy appends a copy step from the materialized Git context (src is context-relative) to an absolute guest path.

func (TemplateSpec) FromImage added in v0.4.0

func (s TemplateSpec) FromImage(image string) TemplateSpec

FromImage bases the template on a Tenki-managed image ID or registry image ref.

func (TemplateSpec) FromSnapshot added in v0.4.0

func (s TemplateSpec) FromSnapshot(snapshotID string) TemplateSpec

FromSnapshot bases the template on a parent snapshot.

func (TemplateSpec) FromTemplate added in v0.4.0

func (s TemplateSpec) FromTemplate(templateID string) TemplateSpec

FromTemplate bases the template on the current publication of a parent template.

func (TemplateSpec) Mkdir added in v0.4.0

func (s TemplateSpec) Mkdir(path string, opts ...MkdirOptions) TemplateSpec

Mkdir appends a directory creation step.

func (TemplateSpec) Npm added in v0.4.0

func (s TemplateSpec) Npm(packages ...string) TemplateSpec

Npm appends an npm package install step.

func (TemplateSpec) Pip added in v0.4.0

func (s TemplateSpec) Pip(packages ...string) TemplateSpec

Pip appends a pip package install step.

func (TemplateSpec) ProcessCompose added in v0.4.0

func (s TemplateSpec) ProcessCompose(configPath string, opts ...ProcessComposeOptions) TemplateSpec

ProcessCompose declares a process-compose runtime supervisor. The config path and env files are workdir-relative; Tenki owns supervisor execution.

func (TemplateSpec) ReadyWhen added in v0.4.0

func (s TemplateSpec) ReadyWhen(ready ReadyWhen) TemplateSpec

ReadyWhen sets the runtime readiness contract.

func (TemplateSpec) Remove added in v0.4.0

func (s TemplateSpec) Remove(path string, opts ...RemoveOptions) TemplateSpec

Remove appends a path removal step.

func (TemplateSpec) Rename added in v0.4.0

func (s TemplateSpec) Rename(src, dest string, opts ...StepOptions) TemplateSpec

Rename appends a rename step between absolute guest paths.

func (TemplateSpec) Resources added in v0.4.0

func (s TemplateSpec) Resources(resources TemplateResources) TemplateSpec

Resources sets CPU/memory/disk defaults for builds and launched sandboxes.

func (TemplateSpec) RestartPolicy added in v0.4.0

func (s TemplateSpec) RestartPolicy(policy TemplateRestartPolicy) TemplateSpec

RestartPolicy sets the boot/manual runtime restart policy.

func (TemplateSpec) Run added in v0.4.0

func (s TemplateSpec) Run(command string, opts ...RunStepOptions) TemplateSpec

Run appends a shell-form command step (executed with sh -lc).

func (TemplateSpec) RunArgs added in v0.4.0

func (s TemplateSpec) RunArgs(argv []string, opts ...RunStepOptions) TemplateSpec

RunArgs appends an argv-form command step (no shell).

func (TemplateSpec) RuntimeEnv added in v0.4.0

func (s TemplateSpec) RuntimeEnv(env map[string]string) TemplateSpec

RuntimeEnv merges persisted runtime environment variables. A runtime entrypoint (Start, StartArgs, or ProcessCompose) is still required.

func (TemplateSpec) RuntimeRunAt added in v0.4.0

func (s TemplateSpec) RuntimeRunAt(runAt RunAt) TemplateSpec

RuntimeRunAt sets when the declared runtime starts (boot is the server default).

func (TemplateSpec) SnapshotMode added in v0.4.0

func (s TemplateSpec) SnapshotMode(mode SnapshotMode) TemplateSpec

SnapshotMode selects filesystem or memory capture for build-time runtime.

func (TemplateSpec) Start added in v0.4.0

func (s TemplateSpec) Start(command string, opts ...StartOptions) TemplateSpec

Start declares a shell-form runtime start command.

func (TemplateSpec) StartArgs added in v0.4.0

func (s TemplateSpec) StartArgs(argv []string, opts ...StartOptions) TemplateSpec

StartArgs declares an argv-form runtime start command.

func (TemplateSpec) StopGrace added in v0.4.0

func (s TemplateSpec) StopGrace(grace time.Duration) TemplateSpec

StopGrace sets the graceful stop window used before filesystem snapshots.

func (s TemplateSpec) Symlink(target, path string, opts ...StepOptions) TemplateSpec

Symlink appends a symlink step: path becomes a link pointing at target.

func (TemplateSpec) ToJSON added in v0.4.0

func (s TemplateSpec) ToJSON() ([]byte, error)

ToJSON emits authored JSON with protobuf field encoding and short enum values. Serialization succeeds even for invalid specs; use Validate for violations.

func (TemplateSpec) Validate added in v0.4.0

func (s TemplateSpec) Validate() error

Validate reports every violation in the spec as a *TemplateSpecValidationError. It mirrors the obvious server contract rules; the server remains authoritative.

func (TemplateSpec) WithGitContext added in v0.4.0

func (s TemplateSpec) WithGitContext(gitContext GitContext) TemplateSpec

WithGitContext sets the backend-fetched Git build context.

func (TemplateSpec) Workdir added in v0.4.0

func (s TemplateSpec) Workdir(dir string) TemplateSpec

Workdir sets the default directory for checkout, build steps, and runtime.

func (TemplateSpec) WriteFile added in v0.4.0

func (s TemplateSpec) WriteFile(path, content string, opts ...WriteFileOptions) TemplateSpec

WriteFile appends an inline small-file write step.

type TemplateSpecSource added in v0.5.0

type TemplateSpecSource interface {
	string | *Template
}

TemplateSpecSource identifies a typed template by ID or resource object.

type TemplateSpecValidationError added in v0.4.0

type TemplateSpecValidationError struct {
	Violations []TemplateSpecViolation
}

TemplateSpecValidationError carries every violation found in a spec, from local Validate calls or from server-side submission failures.

func (*TemplateSpecValidationError) Error added in v0.4.0

func (*TemplateSpecValidationError) Unwrap added in v0.4.0

func (e *TemplateSpecValidationError) Unwrap() error

type TemplateSpecViolation added in v0.4.0

type TemplateSpecViolation struct {
	Field   string
	Rule    string
	Message string
}

TemplateSpecViolation is one field-addressable template spec violation. Field uses canonical protobuf JSON names (for example "runtime.readyWhen").

type TemplateVisibility

type TemplateVisibility string

TemplateVisibility mirrors template visibility states from the service contract.

const (
	TemplateVisibilityUnspecified TemplateVisibility = "UNSPECIFIED"
	TemplateVisibilityPrivate     TemplateVisibility = "PRIVATE"
	TemplateVisibilityPublic      TemplateVisibility = "PUBLIC"
)

type TunnelTerminationReason

type TunnelTerminationReason string
const (
	TunnelTerminationSDKClosed        TunnelTerminationReason = "sdk_closed"
	TunnelTerminationHostClosed       TunnelTerminationReason = "host_closed"
	TunnelTerminationHostError        TunnelTerminationReason = "host_error"
	TunnelTerminationEngineTerminated TunnelTerminationReason = "engine_terminated"
	TunnelTerminationEngineDraining   TunnelTerminationReason = "engine_draining"
	TunnelTerminationTransportError   TunnelTerminationReason = "transport_error"
	TunnelTerminationTimeout          TunnelTerminationReason = "timeout"
)

type UpdateSessionOption

type UpdateSessionOption interface {
	// contains filtered or unexported methods
}

UpdateSessionOption configures Session.Update behavior.

func WithSetSticky

func WithSetSticky(sticky bool) UpdateSessionOption

WithSetSticky toggles the sticky flag on Update.

type UpdateSnapshotOption

type UpdateSnapshotOption interface {
	// contains filtered or unexported methods
}

UpdateSnapshotOption configures Client.UpdateSnapshot behavior.

func WithExpiresAt

func WithExpiresAt(expiresAt time.Time) UpdateSnapshotOption

WithExpiresAt sets snapshot expiration on update requests.

func WithoutExpiresAt

func WithoutExpiresAt() UpdateSnapshotOption

WithoutExpiresAt clears snapshot expiration on update requests.

type UpdateVolumeOption

type UpdateVolumeOption interface {
	// contains filtered or unexported methods
}

UpdateVolumeOption configures Client.UpdateVolume behavior.

type Volume

type Volume struct {
	ID                string
	WorkspaceID       string
	Name              string
	SizeBytes         int64
	State             VolumeState
	CreatedAt         time.Time
	UpdatedAt         time.Time
	Tags              []string
	ActiveAttachments []VolumeAttachment
}

Volume is the SDK view of a persistent sandbox volume.

func (*Volume) IsDeletable

func (v *Volume) IsDeletable() bool

IsDeletable returns true when the volume has no active attachments and can be deleted without error.

type VolumeAttachment

type VolumeAttachment struct {
	ID        string
	VolumeID  string
	SessionID string
	MountPath string
	ReadOnly  bool
	State     string
}

VolumeAttachment is an active attachment of a volume to a session.

type VolumeMount

type VolumeMount struct {
	VolumeID  string
	MountPath string
	ReadOnly  bool
	State     string
}

VolumeMount configures one session volume attachment.

type VolumeOption

type VolumeOption interface {
	// contains filtered or unexported methods
}

VolumeOption configures per-volume attachment behavior.

func WithReadOnly

func WithReadOnly() VolumeOption

WithReadOnly mounts a volume read-only.

type VolumeState

type VolumeState string

VolumeState mirrors persistent volume lifecycle states from the service contract.

const (
	VolumeStateUnspecified VolumeState = "UNSPECIFIED"
	VolumeStateAvailable   VolumeState = "AVAILABLE"
	VolumeStateDeleting    VolumeState = "DELETING"
	VolumeStateDeleted     VolumeState = "DELETED"
	VolumeStateInUse       VolumeState = "IN_USE"
)

func (VolumeState) IsReady

func (s VolumeState) IsReady() bool

IsReady returns true if the volume is available for use.

func (VolumeState) IsTerminal

func (s VolumeState) IsTerminal() bool

IsTerminal returns true if the volume has reached a final state.

type WriteFileOptions added in v0.4.0

type WriteFileOptions struct {
	Name string
	Mode fs.FileMode
}

WriteFileOptions configures one write-file step.

type WriteStreamOptions

type WriteStreamOptions struct {
	Mode     uint32
	Truncate bool
	Sync     bool
}

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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