Documentation
¶
Overview ¶
Package sandbox provides the standalone Go SDK for Genesis Sandbox, including both the low-level HTTP client and the higher-level session helpers.
Sandbox operates in two modes:
- Job mode (default): each Run composes SubmitJob + WaitJob
- Session mode (after Open): Run reuses the same container (ExecNamedSession)
File operations (Upload/Download/Files) auto-trigger Open() if not already open.
Quick Start — Job Mode (one-shot) ¶
result, err := sandbox.QuickPython(ctx, client, `print("hello")`)
Session Mode — stateful multi-step ¶
sb, err := sandbox.New(client, sandbox.WithHints("runtime.python"))
if err != nil { ... }
defer sb.Close()
sb.Open(ctx)
sb.Upload(ctx, "input.csv", reader)
result, err := sb.RunPython(ctx, `
import pandas as pd
df = pd.read_csv("input.csv")
print(df.describe())
`)
Concurrent Fan-out (Job mode per job) ¶
results, err := sandbox.RunBatch(ctx, client, []sandbox.BatchJob{
{CmdOrCode: "print(6*7)", Opts: []sandbox.ExecOption{sandbox.WithLang("python")}},
{CmdOrCode: "echo $((6*7))", Opts: []sandbox.ExecOption{sandbox.WithLang("shell")}},
{CmdOrCode: "console.log(6*7)", Opts: []sandbox.ExecOption{sandbox.WithLang("javascript")}},
})
Package sandbox provides a high-level, dual-mode client for Genesis Sandbox.
Default Job mode: each Run submits and waits for an independent Job. After Open(): enters Session mode where Run reuses the same container (ExecNamedSession). File operations (Upload/Download/Files) auto-trigger Open() if not already open.
Index ¶
- Constants
- Variables
- func IsEndOfStream(err error) bool
- func MetadataDelete() *string
- func MetadataValue(value string) *string
- type APIError
- type Artifact
- type AuditEvent
- type AuditEventList
- type AuditQuery
- type BatchJob
- type BatchResult
- func RunBatch(ctx context.Context, client *Client, jobs []BatchJob, baseOpts ...Option) ([]BatchResult, error)
- func RunBatchThrottled(ctx context.Context, client *Client, jobs []BatchJob, maxConcurrent int, ...) ([]BatchResult, error)
- func RunSequential(ctx context.Context, sb *Sandbox, jobs []BatchJob) ([]BatchResult, error)
- type BuildDependencyRequest
- type CatalogCard
- type CatalogQuery
- type CatalogResponse
- type Client
- func (c *Client) BuildDependencies(ctx context.Context, req BuildDependencyRequest) (*DependencyBuild, error)
- func (c *Client) CancelExec(ctx context.Context, sessionID, execID string) error
- func (c *Client) CancelJob(ctx context.Context, jobID string) error
- func (c *Client) CreateSession(ctx context.Context, req CreateSessionRequest) (*Session, error)
- func (c *Client) CreateWorkspace(ctx context.Context, req CreateWorkspaceRequest) (*Workspace, error)
- func (c *Client) DeleteSession(ctx context.Context, sessionID string) error
- func (c *Client) DeleteWorkspace(ctx context.Context, workspaceID string) error
- func (c *Client) Destroy(ctx context.Context, sandboxID string) error
- func (c *Client) DownloadArtifact(ctx context.Context, artifactID string) (io.ReadCloser, error)
- func (c *Client) DownloadSessionFile(ctx context.Context, sessionID, workspacePath string) (io.ReadCloser, *WorkspaceFileInfo, error)
- func (c *Client) ExecLogEvents(ctx context.Context, sessionID, execID string, cursor int) (*SSEStream, error)
- func (c *Client) ExecNamedSession(ctx context.Context, sessionID string, req ExecSessionRequest) (*ExecSessionResult, error)
- func (c *Client) ExecSession(ctx context.Context, sandboxID string, req ExecSessionRequest) (*ExecSessionResult, error)
- func (c *Client) ExecSessionAsync(ctx context.Context, sessionID string, req ExecSessionRequest) (*ExecRecord, error)
- func (c *Client) GetCatalog(ctx context.Context, query CatalogQuery) (*CatalogResponse, error)
- func (c *Client) GetDependencyBuild(ctx context.Context, fingerprint string) (*DependencyBuild, error)
- func (c *Client) GetExec(ctx context.Context, sessionID, execID string) (*ExecRecord, error)
- func (c *Client) GetJob(ctx context.Context, jobID string) (*JobResult, error)
- func (c *Client) GetSandbox(ctx context.Context, sandboxID string) (*SandboxLease, error)
- func (c *Client) GetSession(ctx context.Context, sessionID string) (*Session, error)
- func (c *Client) GetSessionContext(ctx context.Context, sessionID string) (*SessionContext, error)
- func (c *Client) GetViewer(ctx context.Context, sandboxID string) (*ViewerDescriptor, error)
- func (c *Client) GetWorkspace(ctx context.Context, workspaceID string) (*Workspace, error)
- func (c *Client) JobLogEvents(ctx context.Context, jobID string, cursor int) (*SSEStream, error)
- func (c *Client) JobLogs(ctx context.Context, jobID string, cursor int) (io.ReadCloser, error)
- func (c *Client) Lease(ctx context.Context, req LeaseRequest) (*SandboxLease, error)
- func (c *Client) ListAuditEvents(ctx context.Context, query AuditQuery) (*AuditEventList, error)
- func (c *Client) ListJobArtifacts(ctx context.Context, jobID string, offset, limit int) ([]Artifact, error)
- func (c *Client) ListJobs(ctx context.Context, status string, limit, offset int) (*JobList, error)
- func (c *Client) ListSandboxes(ctx context.Context) ([]SandboxLease, error)
- func (c *Client) ListSessionExecs(ctx context.Context, sessionID string, query ExecListQuery) (*ExecRecordList, error)
- func (c *Client) ListSessionFiles(ctx context.Context, sessionID, workspacePath string, recursive bool, ...) (*WorkspaceListResult, error)
- func (c *Client) MkdirSessionDir(ctx context.Context, sessionID, workspacePath string) (*WorkspaceFileInfo, error)
- func (c *Client) PatchSandbox(ctx context.Context, sandboxID string, metadata map[string]string, ...) (*SandboxLease, error)
- func (c *Client) PatchSandboxMetadata(ctx context.Context, sandboxID string, metadata SandboxMetadataPatch, ...) (*SandboxLease, error)
- func (c *Client) PatchSessionContext(ctx context.Context, sessionID string, patch SessionContext) (*SessionContext, error)
- func (c *Client) Release(ctx context.Context, sandboxID string) error
- func (c *Client) RemoveSessionFile(ctx context.Context, sessionID, workspacePath string, recursive bool) error
- func (c *Client) Renew(ctx context.Context, sandboxID string, extendSeconds int) (*SandboxLease, error)
- func (c *Client) RenewSession(ctx context.Context, sessionID string, extendSeconds int) (*Session, error)
- func (c *Client) ResolveEnvironment(ctx context.Context, req ResolveEnvironmentRequest) (*EnvironmentResolution, error)
- func (c *Client) StartGUI(ctx context.Context, sandboxID string, req StartGUIRequest) (*ViewerDescriptor, error)
- func (c *Client) StatSessionFile(ctx context.Context, sessionID, workspacePath string) (*WorkspaceFileInfo, error)
- func (c *Client) StopGUI(ctx context.Context, sandboxID string) error
- func (c *Client) StreamExecLogs(ctx context.Context, sessionID, execID string, cursor int) (io.ReadCloser, error)
- func (c *Client) SubmitJob(ctx context.Context, req SubmitJobRequest) (*JobResult, error)
- func (c *Client) SubmitJobAndWait(ctx context.Context, req SubmitJobRequest, wait time.Duration) (*JobResult, error)
- func (c *Client) SuspendSession(ctx context.Context, sessionID string, opts ...SuspendOption) (*Session, error)
- func (c *Client) UploadJobFile(ctx context.Context, jobID string, name string, r io.Reader) (*Artifact, error)
- func (c *Client) UploadSessionFile(ctx context.Context, sessionID, workspacePath string, content io.Reader) (*WorkspaceFileInfo, error)
- func (c *Client) UploadSessionFileConditional(ctx context.Context, sessionID, workspacePath string, content io.Reader, ...) (*WorkspaceFileInfo, error)
- func (c *Client) WaitJob(ctx context.Context, jobID string) (*JobResult, error)
- func (c *Client) WaitJobWithOptions(ctx context.Context, jobID string, opts WaitJobOptions) (*JobResult, error)
- func (c *Client) WaitViewer(ctx context.Context, sandboxID string, opts WaitViewerOptions) (*ViewerDescriptor, error)
- type Config
- type CreateSessionRequest
- type CreateWorkspaceRequest
- type DependencyBuild
- type EffectiveEnvironment
- type EnvHints
- type EnvironmentResolution
- type EnvironmentSelector
- type ExecHandle
- func (h *ExecHandle) Cancel(ctx context.Context) error
- func (h *ExecHandle) Events(ctx context.Context, cursor int) (*SSEStream, error)
- func (h *ExecHandle) ID() string
- func (h *ExecHandle) Logs(ctx context.Context, cursor int) (io.ReadCloser, error)
- func (h *ExecHandle) Status(ctx context.Context) (*ExecRecord, error)
- func (h *ExecHandle) Wait(ctx context.Context) (*ExecResult, error)
- func (h *ExecHandle) WaitWithOptions(ctx context.Context, opts WaitExecOptions) (*ExecResult, error)
- type ExecListQuery
- type ExecOption
- type ExecRecord
- type ExecRecordList
- type ExecResult
- type ExecSessionRequest
- type ExecSessionResult
- type FileEntry
- type FileOption
- type JobList
- type JobResult
- type LeaseRequest
- type Logger
- type Option
- func WithEnv(env map[string]string) Option
- func WithHeartbeatDisabled() Option
- func WithHeartbeatInterval(d time.Duration) Option
- func WithHints(capabilities ...string) Option
- func WithIdempotencyKey(key string) Option
- func WithLogger(logger Logger) Option
- func WithMetadata(kv map[string]string) Option
- func WithProfile(name string) Option
- func WithProfileRevision(name, revision string) Option
- func WithResolutionID(id string) Option
- func WithSessionTTL(seconds int) Option
- func WithStrictHints(capabilities ...string) Option
- func WithWorkspaceID(workspaceID string) Option
- func WithWorkspaceRetention(mode string, ttlSeconds int) Option
- type ProfileFeatures
- type ProfileLimits
- type ProfileRef
- type ResolveEnvironmentRequest
- type SSEEvent
- type SSEStream
- type Sandbox
- func (sb *Sandbox) Close() error
- func (sb *Sandbox) CloseContext(ctx context.Context) error
- func (sb *Sandbox) Download(ctx context.Context, path string) (io.ReadCloser, error)
- func (sb *Sandbox) Files(ctx context.Context, path string, opts ...FileOption) ([]FileEntry, error)
- func (sb *Sandbox) IsClosed() bool
- func (sb *Sandbox) IsOpen() bool
- func (sb *Sandbox) Mkdir(ctx context.Context, path string) error
- func (sb *Sandbox) Open(ctx context.Context) error
- func (sb *Sandbox) Remove(ctx context.Context, path string, recursive bool) error
- func (sb *Sandbox) Run(ctx context.Context, cmdOrCode string, opts ...ExecOption) (*ExecResult, error)
- func (sb *Sandbox) RunAsync(ctx context.Context, cmdOrCode string, opts ...ExecOption) (*ExecHandle, error)
- func (sb *Sandbox) RunNode(ctx context.Context, code string) (*ExecResult, error)
- func (sb *Sandbox) RunPython(ctx context.Context, code string) (*ExecResult, error)
- func (sb *Sandbox) RunShell(ctx context.Context, script string) (*ExecResult, error)
- func (sb *Sandbox) SessionID() string
- func (sb *Sandbox) SetCwd(ctx context.Context, cwd string) error
- func (sb *Sandbox) SetEnv(ctx context.Context, env map[string]string) error
- func (sb *Sandbox) StatFile(ctx context.Context, path string) (*FileEntry, error)
- func (sb *Sandbox) Suspend(ctx context.Context) error
- func (sb *Sandbox) Upload(ctx context.Context, path string, content io.Reader) error
- func (sb *Sandbox) WorkspaceID() string
- type SandboxLease
- type SandboxMetadataPatch
- type Session
- type SessionContext
- type StartGUIRequest
- type SubmitJobRequest
- type SuspendOption
- type ViewerDescriptor
- type WaitExecOptions
- type WaitJobOptions
- type WaitViewerOptions
- type Workspace
- type WorkspaceFileInfo
- type WorkspaceListResult
Constants ¶
const ( // DefaultSessionTTL is the default server-side session TTL requested by Open. DefaultSessionTTL = 300 // DefaultHeartbeatInterval is the fixed heartbeat interval used by the // auto-renew loop. It must stay well below the server lease timeout / 2. DefaultHeartbeatInterval = 30 * time.Second // DefaultHeartbeatExtendSeconds is how many seconds each heartbeat extends the lease. DefaultHeartbeatExtendSeconds = 90 )
Variables ¶
var ErrClosed = errors.New("sandbox: client object is closed")
var ErrNotModified = errors.New("not modified")
ErrNotModified is returned by conditional requests (If-None-Match) when the server responds 304 Not Modified; the cached representation is still valid.
var ErrNotOpened = errors.New("sandbox: session not opened; call Open() first")
ErrNotOpened is returned when a Session-only operation is called before Open().
Functions ¶
func IsEndOfStream ¶
func MetadataDelete ¶
func MetadataDelete() *string
func MetadataValue ¶
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
ErrorCode string
Message string
RequestID string
Details map[string]any
RetryAfter time.Duration
}
APIError is a structured error returned by the Sandbox Service.
type Artifact ¶
type Artifact struct {
ArtifactID string `json:"artifact_id"`
TenantID string `json:"tenant_id"`
WorkspaceID string `json:"workspace_id"`
JobID string `json:"job_id"`
Name string `json:"name"`
Path string `json:"path"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
MIME string `json:"mime"`
CreatedAt time.Time `json:"created_at"`
}
type AuditEvent ¶
type AuditEvent struct {
EventID string `json:"event_id"`
TenantID string `json:"tenant_id"`
UserID string `json:"user_id,omitempty"`
PrincipalID string `json:"principal_id,omitempty"`
KeyID string `json:"key_id,omitempty"`
Action string `json:"action"`
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id,omitempty"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
TraceID string `json:"trace_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type AuditEventList ¶
type AuditEventList struct {
Items []AuditEvent `json:"items"`
NextOffset int `json:"next_offset,omitempty"`
Total int `json:"total"`
}
type AuditQuery ¶
type BatchJob ¶
type BatchJob struct {
CmdOrCode string // command string or source code
Opts []ExecOption // per-job options (WithLang, WithTimeout, etc.)
}
BatchJob defines a single job to run.
type BatchResult ¶
type BatchResult struct {
Index int
Result *ExecResult
Err error
}
BatchResult holds the outcome of one BatchJob.
func RunBatch ¶
func RunBatch( ctx context.Context, client *Client, jobs []BatchJob, baseOpts ...Option, ) ([]BatchResult, error)
RunBatch creates one Sandbox per job (Job mode) and runs all jobs CONCURRENTLY. Each job uses SubmitJob/WaitJob independently. Individual failures do not abort other jobs.
func RunBatchThrottled ¶
func RunBatchThrottled( ctx context.Context, client *Client, jobs []BatchJob, maxConcurrent int, baseOpts ...Option, ) ([]BatchResult, error)
RunBatchThrottled is like RunBatch but limits concurrent sandboxes to maxConcurrent.
func RunSequential ¶
RunSequential runs all jobs on a single opened Sandbox (Session mode, shared state). The Sandbox must already be Open()'d by the caller.
func (*BatchResult) OK ¶
func (r *BatchResult) OK() bool
OK returns true when the job succeeded without error.
type BuildDependencyRequest ¶
type BuildDependencyRequest struct {
Environment *EnvironmentSelector `json:"environment,omitempty"`
ResolutionID string `json:"resolution_id,omitempty"`
Language string `json:"language,omitempty"`
Manifest string `json:"manifest,omitempty"`
Lockfile string `json:"lockfile,omitempty"`
Packages []string `json:"packages,omitempty"`
}
type CatalogCard ¶
type CatalogCard struct {
ProfileName string `json:"name"`
ProfileRevision string `json:"profile_revision"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Capabilities []string `json:"capabilities"`
Tags []string `json:"tags,omitempty"`
UseWhen []string `json:"use_when,omitempty"`
AvoidWhen []string `json:"avoid_when,omitempty"`
Limits *ProfileLimits `json:"limits,omitempty"`
Features *ProfileFeatures `json:"features,omitempty"`
}
CatalogCard is a single profile entry in the environment catalog.
type CatalogQuery ¶
type CatalogQuery struct {
Capability string // Filter by capability (comma-separated AND)
Tag string // Filter by tag
Limit int
Offset int
IfNoneMatch string // ETag conditional request
}
CatalogQuery holds query parameters for GetCatalog.
type CatalogResponse ¶
type CatalogResponse struct {
Items []CatalogCard `json:"items"`
CapabilityVocabulary []string `json:"capability_vocabulary,omitempty"`
DefaultProfile string `json:"default_profile,omitempty"`
NextOffset int `json:"next_offset,omitempty"`
Total int `json:"total"`
Revision string `json:"-"`
}
CatalogResponse is the response from GET /v1/environment/catalog.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) BuildDependencies ¶
func (c *Client) BuildDependencies(ctx context.Context, req BuildDependencyRequest) (*DependencyBuild, error)
func (*Client) CancelExec ¶
CancelExec cancels a running or queued async exec.
func (*Client) CreateSession ¶
func (*Client) CreateWorkspace ¶
func (*Client) DeleteSession ¶
func (*Client) DeleteWorkspace ¶
func (*Client) DownloadArtifact ¶
func (*Client) DownloadSessionFile ¶
func (c *Client) DownloadSessionFile(ctx context.Context, sessionID, workspacePath string) (io.ReadCloser, *WorkspaceFileInfo, error)
func (*Client) ExecLogEvents ¶
func (*Client) ExecNamedSession ¶
func (c *Client) ExecNamedSession(ctx context.Context, sessionID string, req ExecSessionRequest) (*ExecSessionResult, error)
func (*Client) ExecSession ¶
func (c *Client) ExecSession(ctx context.Context, sandboxID string, req ExecSessionRequest) (*ExecSessionResult, error)
func (*Client) ExecSessionAsync ¶
func (c *Client) ExecSessionAsync(ctx context.Context, sessionID string, req ExecSessionRequest) (*ExecRecord, error)
ExecSessionAsync submits an async exec for the given session.
func (*Client) GetCatalog ¶
func (c *Client) GetCatalog(ctx context.Context, query CatalogQuery) (*CatalogResponse, error)
GetCatalog retrieves the environment profile catalog.
func (*Client) GetDependencyBuild ¶
func (*Client) GetSandbox ¶
func (*Client) GetSession ¶
func (*Client) GetSessionContext ¶
GetSessionContext retrieves the session-level cwd and env.
func (*Client) GetWorkspace ¶
func (*Client) JobLogEvents ¶
func (*Client) Lease ¶
func (c *Client) Lease(ctx context.Context, req LeaseRequest) (*SandboxLease, error)
func (*Client) ListAuditEvents ¶
func (c *Client) ListAuditEvents(ctx context.Context, query AuditQuery) (*AuditEventList, error)
func (*Client) ListJobArtifacts ¶
func (*Client) ListSandboxes ¶
func (c *Client) ListSandboxes(ctx context.Context) ([]SandboxLease, error)
func (*Client) ListSessionExecs ¶
func (c *Client) ListSessionExecs(ctx context.Context, sessionID string, query ExecListQuery) (*ExecRecordList, error)
func (*Client) ListSessionFiles ¶
func (*Client) MkdirSessionDir ¶
func (*Client) PatchSandbox ¶
func (*Client) PatchSandboxMetadata ¶
func (c *Client) PatchSandboxMetadata(ctx context.Context, sandboxID string, metadata SandboxMetadataPatch, resourceVersion int64) (*SandboxLease, error)
func (*Client) PatchSessionContext ¶
func (c *Client) PatchSessionContext(ctx context.Context, sessionID string, patch SessionContext) (*SessionContext, error)
PatchSessionContext modifies the session-level cwd and/or env.
func (*Client) RemoveSessionFile ¶
func (*Client) RenewSession ¶
func (c *Client) RenewSession(ctx context.Context, sessionID string, extendSeconds int) (*Session, error)
RenewSession 续期 session(心跳续约),同时延长底层沙箱租约。 extendSeconds 为本次续期延长的秒数,服务端受 max_lease_timeout 硬上限约束。
func (*Client) ResolveEnvironment ¶
func (c *Client) ResolveEnvironment(ctx context.Context, req ResolveEnvironmentRequest) (*EnvironmentResolution, error)
ResolveEnvironment performs a two-phase resolution and returns a principal-bound ticket.
func (*Client) StartGUI ¶
func (c *Client) StartGUI(ctx context.Context, sandboxID string, req StartGUIRequest) (*ViewerDescriptor, error)
func (*Client) StatSessionFile ¶
func (*Client) StreamExecLogs ¶
func (c *Client) StreamExecLogs(ctx context.Context, sessionID, execID string, cursor int) (io.ReadCloser, error)
StreamExecLogs opens an SSE stream for exec logs. Caller must close the returned ReadCloser.
func (*Client) SubmitJobAndWait ¶
func (*Client) SuspendSession ¶
func (c *Client) SuspendSession(ctx context.Context, sessionID string, opts ...SuspendOption) (*Session, error)
SuspendSession releases the ephemeral runtime while preserving the session workspace. If force is true, running execs are cancelled before suspending.
func (*Client) UploadJobFile ¶
func (*Client) UploadSessionFile ¶
func (*Client) UploadSessionFileConditional ¶
func (c *Client) UploadSessionFileConditional(ctx context.Context, sessionID, workspacePath string, content io.Reader, ifMatch string, createOnly bool) (*WorkspaceFileInfo, error)
UploadSessionFileConditional performs an optimistic conditional write. ifMatch accepts the SHA-256/ETag returned by a previous read; createOnly maps to If-None-Match: *.
func (*Client) WaitJobWithOptions ¶
func (*Client) WaitViewer ¶
func (c *Client) WaitViewer(ctx context.Context, sandboxID string, opts WaitViewerOptions) (*ViewerDescriptor, error)
type CreateSessionRequest ¶
type CreateSessionRequest struct {
Environment *EnvironmentSelector `json:"environment,omitempty"`
ResolutionID string `json:"resolution_id,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
StatePolicy string `json:"state_policy,omitempty"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
WorkspaceRetention string `json:"workspace_retention,omitempty"`
WorkspaceTTLSeconds int `json:"workspace_ttl_seconds,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
Env map[string]string `json:"env,omitempty"` // SDK convenience: create session, then patch session context env.
Metadata map[string]string `json:"metadata,omitempty"`
}
type CreateWorkspaceRequest ¶
type DependencyBuild ¶
type DependencyBuild struct {
Fingerprint string `json:"fingerprint"`
TenantID string `json:"tenant_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
ProfileName string `json:"profile_name"`
ProfileRevision string `json:"profile_revision"`
Language string `json:"language"`
Status string `json:"status"`
CachePath string `json:"cache_path,omitempty"`
ReadOnly bool `json:"read_only"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type EffectiveEnvironment ¶
type EffectiveEnvironment struct {
ProfileName string `json:"profile_name"`
ProfileRevision string `json:"profile_revision,omitempty"`
SelectionMode string `json:"selection_mode"`
SelectionReason []string `json:"selection_reason,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Degraded bool `json:"degraded,omitempty"`
}
EffectiveEnvironment describes the resolved environment in API responses.
type EnvHints ¶
type EnvHints struct {
Capabilities []string `json:"capabilities,omitempty"`
Strict bool `json:"strict,omitempty"`
Description string `json:"description,omitempty"`
}
EnvHints provides capability-based hints for automatic profile selection.
type EnvironmentResolution ¶
type EnvironmentResolution struct {
ResolutionID string `json:"resolution_id"`
ProfileName string `json:"profile_name"`
ProfileRevision string `json:"profile_revision,omitempty"`
SelectionMode string `json:"selection_mode"`
SelectionReason []string `json:"selection_reason,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
ExpiresAt string `json:"expires_at"`
}
EnvironmentResolution is the response from POST /v1/environment:resolve.
type EnvironmentSelector ¶
type EnvironmentSelector struct {
Profile *ProfileRef `json:"profile,omitempty"`
Hints *EnvHints `json:"hints,omitempty"`
}
EnvironmentSelector is the unified entry point for environment selection. Exactly one of Profile or Hints should be provided.
type ExecHandle ¶
type ExecHandle struct {
// contains filtered or unexported fields
}
ExecHandle represents a running or completed async exec.
func (*ExecHandle) Cancel ¶
func (h *ExecHandle) Cancel(ctx context.Context) error
Cancel cancels a running or queued exec.
func (*ExecHandle) Events ¶
Events opens an incrementally decoded SSE log stream. Caller must close it.
func (*ExecHandle) Logs ¶
func (h *ExecHandle) Logs(ctx context.Context, cursor int) (io.ReadCloser, error)
Logs opens an SSE log stream. Caller must close the returned ReadCloser.
func (*ExecHandle) Status ¶
func (h *ExecHandle) Status(ctx context.Context) (*ExecRecord, error)
Status returns the current exec record.
func (*ExecHandle) Wait ¶
func (h *ExecHandle) Wait(ctx context.Context) (*ExecResult, error)
Wait polls GetExec until the exec reaches a terminal state.
func (*ExecHandle) WaitWithOptions ¶
func (h *ExecHandle) WaitWithOptions(ctx context.Context, opts WaitExecOptions) (*ExecResult, error)
type ExecListQuery ¶
type ExecOption ¶
type ExecOption func(*execOptions)
ExecOption is a functional option for Run / RunAsync.
func WithCallback ¶
func WithCallback(url string) ExecOption
WithCallback sets the async completion callback URL.
func WithExecEnv ¶
func WithExecEnv(env map[string]string) ExecOption
WithExecEnv sets per-execution environment variables (merged with session env).
func WithLang ¶
func WithLang(lang string) ExecOption
WithLang marks the cmdOrCode argument as source code in the given language.
func WithTimeout ¶
func WithTimeout(d time.Duration) ExecOption
WithTimeout sets a per-execution timeout.
func WithWorkingDir ¶
func WithWorkingDir(dir string) ExecOption
WithWorkingDir sets the working directory for this execution.
type ExecRecord ¶
type ExecRecord struct {
ExecID string `json:"exec_id"`
SessionID string `json:"session_id"`
Status string `json:"status"` // queued|running|succeeded|failed|cancelled
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
StdoutTruncated bool `json:"stdout_truncated,omitempty"`
StderrTruncated bool `json:"stderr_truncated,omitempty"`
WorkingDir string `json:"working_dir,omitempty"`
EffectiveEnvironment *EffectiveEnvironment `json:"effective_environment,omitempty"`
LogsURL string `json:"logs_url,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
ExecRecord represents an async exec status record (Phase 2).
type ExecRecordList ¶
type ExecRecordList struct {
Items []ExecRecord `json:"items"`
NextCursor string `json:"next_cursor,omitempty"`
Total int `json:"total"`
}
type ExecResult ¶
type ExecResult struct {
ExitCode int
Stdout string
Stderr string
StdoutTruncated bool
StderrTruncated bool
ErrorCode string // timeout, cancelled, oom, etc.
EffectiveEnvironment *EffectiveEnvironment
}
ExecResult holds the output of a single execution.
func QuickPython ¶
func QuickPython(ctx context.Context, client *Client, code string, opts ...Option) (*ExecResult, error)
QuickPython executes Python code via a one-shot Job.
func QuickRun ¶
func QuickRun(ctx context.Context, client *Client, command string, opts ...Option) (*ExecResult, error)
QuickRun executes a single command via a one-shot Job. No Workspace or Session is created. For simple one-shot execution.
func (*ExecResult) OK ¶
func (r *ExecResult) OK() bool
OK returns true when ExitCode == 0 and no error code is set.
type ExecSessionRequest ¶
type ExecSessionRequest struct {
Command []string `json:"command,omitempty"`
Code string `json:"code,omitempty"`
Language string `json:"language,omitempty"`
WorkingDir string `json:"working_dir,omitempty"`
Env map[string]string `json:"env,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
CallbackURL string `json:"callback_url,omitempty"` // Async exec only; sync endpoints ignore it.
}
type ExecSessionResult ¶
type ExecSessionResult struct {
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
StdoutTruncated bool `json:"stdout_truncated,omitempty"`
StderrTruncated bool `json:"stderr_truncated,omitempty"`
Environment string `json:"environment"`
SessionID string `json:"session_id,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
SandboxID string `json:"sandbox_id,omitempty"`
Cwd string `json:"cwd,omitempty"`
}
type FileEntry ¶
type FileEntry = WorkspaceFileInfo
FileEntry represents a file or directory in the workspace.
type FileOption ¶
type FileOption func(*fileOptions)
FileOption configures file listing behavior.
func WithFileLimit ¶
func WithFileLimit(n int) FileOption
WithFileLimit sets the maximum entries returned.
type JobResult ¶
type JobResult struct {
JobID string `json:"job_id"`
TenantID string `json:"tenant_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
SandboxID string `json:"sandbox_id"`
TaskType string `json:"task_type,omitempty"`
Operation string `json:"operation,omitempty"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
StdoutTruncated bool `json:"stdout_truncated,omitempty"`
StderrTruncated bool `json:"stderr_truncated,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Error string `json:"error,omitempty"`
ErrorMessage string `json:"-"` // Deprecated: use Error.
DurationMS int64 `json:"duration_ms,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
OutputArtifacts []Artifact `json:"output_artifacts,omitempty"`
LogsURL string `json:"logs_url,omitempty"`
EffectiveEnvironment *EffectiveEnvironment `json:"effective_environment,omitempty"`
}
type LeaseRequest ¶
type LeaseRequest struct {
WorkspaceID string `json:"workspace_id,omitempty"`
Environment *EnvironmentSelector `json:"environment,omitempty"`
ResolutionID string `json:"resolution_id,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
type Option ¶
type Option func(*sandboxOptions)
Option is a functional option for New / QuickRun / RunBatch.
func WithEnv ¶
WithEnv sets job-level environment variables and the default session env. In Session mode, the SDK applies it immediately after CreateSession succeeds.
func WithHeartbeatDisabled ¶
func WithHeartbeatDisabled() Option
WithHeartbeatDisabled turns off the built-in auto-renew heartbeat.
func WithHeartbeatInterval ¶
WithHeartbeatInterval overrides the built-in heartbeat interval.
func WithIdempotencyKey ¶
WithIdempotencyKey sets the idempotency key for session creation.
func WithLogger ¶
WithLogger enables optional SDK diagnostics. The library is silent by default.
func WithMetadata ¶
WithMetadata attaches user metadata to the session/job request.
func WithProfile ¶
WithProfile sets an explicit profile name for environment selection.
func WithProfileRevision ¶
WithProfileRevision sets an explicit profile with a pinned revision.
func WithResolutionID ¶
WithResolutionID uses a pre-resolved environment ticket.
func WithSessionTTL ¶
WithSessionTTL overrides the requested server-side session TTL in seconds.
func WithStrictHints ¶
WithStrictHints sets strict capability hints (fail if not all satisfied).
func WithWorkspaceID ¶
WithWorkspaceID reuses an existing workspace instead of creating a new one.
func WithWorkspaceRetention ¶
WithWorkspaceRetention configures the retention policy for a newly-created workspace.
type ProfileFeatures ¶
type ProfileFeatures struct {
Viewer bool `json:"viewer,omitempty"`
SuspendResume bool `json:"suspend_resume,omitempty"`
}
ProfileFeatures describes optional features supported by a profile.
type ProfileLimits ¶
type ProfileLimits struct {
MaxExecTimeoutSeconds int `json:"max_exec_timeout_seconds,omitempty"`
MaxSessionTTLSeconds int `json:"max_session_ttl_seconds,omitempty"`
WorkspaceQuotaMB int `json:"workspace_quota_mb,omitempty"`
MaxLogBytes int64 `json:"max_log_bytes,omitempty"`
MaxConcurrentExecs int `json:"max_concurrent_execs,omitempty"`
}
ProfileLimits describes resource constraints of a profile.
type ProfileRef ¶
ProfileRef specifies an explicit profile by name (and optional revision).
type ResolveEnvironmentRequest ¶
type ResolveEnvironmentRequest struct {
Environment EnvironmentSelector `json:"environment"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
}
type SSEEvent ¶
SSEEvent is one Server-Sent Event from a Job or Session exec log stream.
func (SSEEvent) DecodeJSON ¶
type SSEStream ¶
type SSEStream struct {
// contains filtered or unexported fields
}
SSEStream incrementally decodes an SSE response. Call Close when finished.
type Sandbox ¶
type Sandbox struct {
// contains filtered or unexported fields
}
Sandbox is the high-level Genesis Sandbox client object. Default Job mode (each Run gets an independent container). Call Open() to enter Session mode (container reuse across Runs).
func New ¶
New creates a Sandbox object. No Session/Workspace is created, no heartbeat started. If WithWorkspaceID is provided, that workspace will be reused on Open().
func (*Sandbox) CloseContext ¶
CloseContext cleans up resources:
- If opened: stops heartbeat + deletes Session (workspace follows retention policy)
- If not opened: no-op
- Workspaces provided via WithWorkspaceID are not deleted (user-owned)
CloseContext is idempotent and safe to call multiple times (use defer).
func (*Sandbox) Download ¶
Download reads a file from the workspace. If not yet opened, auto-triggers Open().
func (*Sandbox) Files ¶
Files lists workspace directory entries. If not yet opened, auto-triggers Open().
func (*Sandbox) Mkdir ¶
Mkdir creates a directory tree in the workspace. If not yet opened, auto-triggers Open().
func (*Sandbox) Open ¶
Open explicitly enters Session mode: creates a Session (with Workspace) and starts heartbeat. After Open(), Run uses ExecNamedSession. Suspend/SetCwd/SetEnv/RunAsync become available. Safe to call concurrently with ensureOpen (file ops); only one session is ever created.
func (*Sandbox) Remove ¶
Remove deletes a file or directory from the workspace. If not yet opened, auto-triggers Open().
func (*Sandbox) Run ¶
func (sb *Sandbox) Run(ctx context.Context, cmdOrCode string, opts ...ExecOption) (*ExecResult, error)
Run executes a command or code and waits for the result.
- Job mode (not opened): composes SubmitJob + WaitJob
- Session mode (after Open): calls ExecNamedSession (reuses container)
The cmdOrCode argument is interpreted as:
- Source code if WithLang is provided (sent as "code" field)
- Shell command otherwise (sent as command: ["/bin/sh", "-c", cmdOrCode])
func (*Sandbox) RunAsync ¶
func (sb *Sandbox) RunAsync(ctx context.Context, cmdOrCode string, opts ...ExecOption) (*ExecHandle, error)
RunAsync submits an async exec (Session mode only) and returns an ExecHandle.
func (*Sandbox) RunNode ¶
RunNode executes Node.js code (equivalent to Run(ctx, code, WithLang("javascript"))).
func (*Sandbox) RunPython ¶
RunPython executes Python code (equivalent to Run(ctx, code, WithLang("python"))).
func (*Sandbox) RunShell ¶
RunShell executes a shell script (equivalent to Run(ctx, script, WithLang("shell"))).
func (*Sandbox) SetEnv ¶
SetEnv modifies the session-level environment variables (Session mode only).
func (*Sandbox) StatFile ¶
StatFile returns metadata for a workspace file. If not yet opened, auto-triggers Open().
func (*Sandbox) Suspend ¶
Suspend releases the runtime (container) while preserving the session workspace. Only available in Session mode.
func (*Sandbox) Upload ¶
Upload writes a file to the workspace. If not yet opened, auto-triggers Open() (transparent upgrade to Session mode).
func (*Sandbox) WorkspaceID ¶
WorkspaceID returns the workspace identifier (empty if not opened and no WithWorkspaceID).
type SandboxLease ¶
type SandboxLease struct {
SandboxID string `json:"sandbox_id"`
LeaseID string `json:"lease_id"`
TenantID string `json:"tenant_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
RuntimeProfile string `json:"runtime_profile"`
ProfileRevision string `json:"profile_revision,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
EffectivePolicy interface{} `json:"effective_policy"`
EffectiveEnvironment *EffectiveEnvironment `json:"effective_environment,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
ResourceVersion int64 `json:"resource_version"`
}
type SandboxMetadataPatch ¶
type Session ¶
type Session struct {
SessionID string `json:"session_id"`
TenantID string `json:"tenant_id"`
UserID string `json:"user_id,omitempty"`
WorkspaceID string `json:"workspace_id"`
RuntimeProfile string `json:"runtime_profile"`
ProfileRevision string `json:"profile_revision,omitempty"`
StatePolicy string `json:"state_policy"`
ActiveSandboxID string `json:"active_sandbox_id,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
Metadata map[string]string `json:"metadata,omitempty"`
ResourceVersion int64 `json:"resource_version"`
EffectiveEnvironment *EffectiveEnvironment `json:"effective_environment,omitempty"`
}
type SessionContext ¶
SessionContext represents the mutable session-level cwd/env state.
type StartGUIRequest ¶
type SubmitJobRequest ¶
type SubmitJobRequest struct {
Environment *EnvironmentSelector `json:"environment,omitempty"`
ResolutionID string `json:"resolution_id,omitempty"`
Code string `json:"code,omitempty"`
Command []string `json:"command,omitempty"`
Language string `json:"language,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
QueueWaitTimeoutSeconds int `json:"queue_wait_timeout_seconds,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
CallbackURL string `json:"callback_url,omitempty"`
InputArtifactIDs []string `json:"input_artifact_ids,omitempty"`
Env map[string]string `json:"env,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
type SuspendOption ¶
type SuspendOption func(*suspendConfig)
SuspendOption configures SuspendSession behavior.
func WithForce ¶
func WithForce() SuspendOption
WithForce cancels all running execs before suspending.
type ViewerDescriptor ¶
type ViewerDescriptor struct {
SandboxID string `json:"sandbox_id"`
RuntimeProfile string `json:"runtime_profile"`
Status string `json:"status"`
Kind string `json:"kind"`
Ready bool `json:"ready"`
PageURL string `json:"page_url,omitempty"`
WebSocketURL string `json:"websocket_url,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
AccessToken string `json:"access_token,omitempty"`
TokenHeader string `json:"token_header,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
RenewOnAccess bool `json:"renew_on_access"`
}
type WaitExecOptions ¶
type WaitJobOptions ¶
type WaitViewerOptions ¶
type Workspace ¶
type Workspace struct {
WorkspaceID string `json:"workspace_id"`
TenantID string `json:"tenant_id"`
UserID string `json:"user_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
Metadata map[string]string `json:"metadata,omitempty"`
RetentionMode string `json:"retention_mode"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
QuotaMB int `json:"quota_mb,omitempty"`
}
type WorkspaceFileInfo ¶
type WorkspaceFileInfo struct {
Path string `json:"path"`
SandboxPath string `json:"sandbox_path,omitempty"`
Environment string `json:"environment"`
Name string `json:"name"`
Kind string `json:"kind"`
Size int64 `json:"size,omitempty"`
SHA256 string `json:"sha256,omitempty"`
MIME string `json:"mime,omitempty"`
ModTime time.Time `json:"mod_time,omitempty"`
}
type WorkspaceListResult ¶
type WorkspaceListResult struct {
Path string `json:"path"`
Entries []WorkspaceFileInfo `json:"entries"`
Truncated bool `json:"truncated"`
Limit int `json:"limit"`
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
job_artifact_sync
command
Package main — Job + Artifact 同步示例
|
Package main — Job + Artifact 同步示例 |
|
production_async
command
Package main — 并发/异步模式示例
|
Package main — 并发/异步模式示例 |
|
production_sync
command
Package main — Session 模式同步示例
|
Package main — Session 模式同步示例 |
|
quickstart
command
Quickstart 展示应用代码推荐采用的稳定 Session 调用方式。
|
Quickstart 展示应用代码推荐采用的稳定 Session 调用方式。 |
|
internal
|
|
|
genapi
Package genapi contains generated protocol models derived from the service OpenAPI contract.
|
Package genapi contains generated protocol models derived from the service OpenAPI contract. |