sandbox

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

genesis-sandbox-client-go

genesis-sandbox-client-go 是独立的 Go SDK 模块,作为 genesis-sandbox HTTP API 的唯一客户端实现。

设计目标

  • 单一公开包:github.com/capemeta/genesis-sandbox-client-go
  • 单一源码来源:SDK 不再和服务仓库双向复制演进
  • 同时覆盖低层 HTTP Client 与高层 Sandbox 会话封装
  • 本地联调优先使用 go.work,而不是在业务模块里提交 replace
  • 协议层与手写 facade 分离:OpenAPI 快照与生成模型放在 internal/genapi

协议生成层

SDK 内部保留一份 api/openapi.yaml 协议快照,并通过 internal/genapi 生成协议模型。

重新生成:

go generate ./internal/genapi

设计约束:

  • internal/genapi 只服务内部协议边界,不直接暴露给 SDK 用户
  • 对外仍然由手写的 sandbox 包提供稳定、易用的 public API
  • 少量高层易用性能力允许在 facade 层做补充,例如 CreateSessionRequest.Env

安装

go get github.com/capemeta/genesis-sandbox-client-go

快速开始

client, err := sandbox.NewClient(sandbox.Config{
    BaseURL: "http://127.0.0.1:18010",
    Token:   os.Getenv("GENESIS_SANDBOX_API_KEY"),
    Timeout: 30 * time.Second,
})
if err != nil {
    return err
}

sb, err := sandbox.New(client, sandbox.WithHints("runtime.python"))
if err != nil {
    return err
}
defer sb.Close()

if err := sb.Open(ctx); err != nil {
    return err
}

result, err := sb.RunPython(ctx, `print("hello")`)
if err != nil {
    return err
}
fmt.Print(result.Stdout)

如果你希望完全零配置,也可以直接 sandbox.New(client),由服务端按默认 Public Profile 解析; 只有在你明确想绑定某个部署内 profile 名时,才建议使用 WithProfile(...)

术语约定

  • profile:显式环境名,例如 code-polyglot-basicoffice-basic。只有在你明确要绑定某个部署内环境时才直接指定。
  • language:代码执行语言,只用于 code 类请求,当前公共值为 pythonnodejavascripttypescript。shell/二进制命令执行直接走 command,不是 language=shell
  • hints:能力提示,用来让服务端自动选环境,例如 runtime.pythonruntime.nodetool.libreoffice。推荐作为跨部署、跨环境的默认写法。
  • resolution_id/v1/environment:resolve 返回的环境解析票据。它不是 profile 名,也不是长期环境身份;适合在一次调用链里复用已解析好的不可变环境。

推荐优先级:

  1. 零配置或跨部署兼容:不传 profile,必要时用 WithHints(...)
  2. 需要指定代码语言:传 language
  3. 需要复用同一已解析环境:传 resolution_id
  4. 只有明确要绑定某个部署内 profile 名时,才直接 WithProfile(...)

本地源码联调

推荐在共同父目录创建 go.work,把服务仓库和 SDK 仓库一起纳入:

go work init ./genesis-sandbox ./genesis-sandbox-client-go

这样:

  • 业务项目 import github.com/capemeta/genesis-sandbox-client-go 时可直接命中本地 SDK 源码
  • 本地跑起来的 genesis-sandbox 服务仍然是独立源码仓库
  • 不需要在仓库内提交 replace ../genesis-sandbox-client-go

CI / Release

  • main 分支 push / PR 会触发 ci,执行 go test ./...
  • 推送形如 v0.1.0 的 tag 会触发 release,先验证再创建 GitHub Release
  • release 会附带源码压缩包与 .sha256 校验文件
  • 如需补发已存在 tag,可手动触发 workflow,并传入 tag

示例

  • examples/quickstart: 推荐入口,包含 Session、文件、异步执行、Suspend/Resume
  • examples/production_sync: Session + WorkspaceFS 主路径
  • examples/production_async: 并发批处理、异步执行、共享 Session
  • examples/job_artifact_sync: Job + Artifact 无状态链路

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

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

View Source
var ErrClosed = errors.New("sandbox: client object is closed")
View Source
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.

View Source
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 IsEndOfStream(err error) bool

func MetadataDelete

func MetadataDelete() *string

func MetadataValue

func MetadataValue(value string) *string

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.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Retryable

func (e *APIError) Retryable() bool

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 AuditQuery struct {
	PrincipalID  string
	KeyID        string
	Action       string
	ResourceType string
	ResourceID   string
	Limit        int
	Offset       int
}

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

func RunSequential(
	ctx context.Context,
	sb *Sandbox,
	jobs []BatchJob,
) ([]BatchResult, error)

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 NewClient

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

func (*Client) BuildDependencies

func (c *Client) BuildDependencies(ctx context.Context, req BuildDependencyRequest) (*DependencyBuild, error)

func (*Client) CancelExec

func (c *Client) CancelExec(ctx context.Context, sessionID, execID string) error

CancelExec cancels a running or queued async exec.

func (*Client) CancelJob

func (c *Client) CancelJob(ctx context.Context, jobID string) error

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, req CreateSessionRequest) (*Session, error)

func (*Client) CreateWorkspace

func (c *Client) CreateWorkspace(ctx context.Context, req CreateWorkspaceRequest) (*Workspace, error)

func (*Client) DeleteSession

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

func (*Client) DeleteWorkspace

func (c *Client) DeleteWorkspace(ctx context.Context, workspaceID string) error

func (*Client) Destroy

func (c *Client) Destroy(ctx context.Context, sandboxID string) error

func (*Client) DownloadArtifact

func (c *Client) DownloadArtifact(ctx context.Context, artifactID string) (io.ReadCloser, error)

func (*Client) DownloadSessionFile

func (c *Client) DownloadSessionFile(ctx context.Context, sessionID, workspacePath string) (io.ReadCloser, *WorkspaceFileInfo, error)

func (*Client) ExecLogEvents

func (c *Client) ExecLogEvents(ctx context.Context, sessionID, execID string, cursor int) (*SSEStream, error)

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 (c *Client) GetDependencyBuild(ctx context.Context, fingerprint string) (*DependencyBuild, error)

func (*Client) GetExec

func (c *Client) GetExec(ctx context.Context, sessionID, execID string) (*ExecRecord, error)

GetExec retrieves the status of an async exec.

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, jobID string) (*JobResult, error)

func (*Client) GetSandbox

func (c *Client) GetSandbox(ctx context.Context, sandboxID string) (*SandboxLease, error)

func (*Client) GetSession

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

func (*Client) GetSessionContext

func (c *Client) GetSessionContext(ctx context.Context, sessionID string) (*SessionContext, error)

GetSessionContext retrieves the session-level cwd and env.

func (*Client) GetViewer

func (c *Client) GetViewer(ctx context.Context, sandboxID string) (*ViewerDescriptor, error)

func (*Client) GetWorkspace

func (c *Client) GetWorkspace(ctx context.Context, workspaceID string) (*Workspace, error)

func (*Client) JobLogEvents

func (c *Client) JobLogEvents(ctx context.Context, jobID string, cursor int) (*SSEStream, error)

func (*Client) JobLogs

func (c *Client) JobLogs(ctx context.Context, jobID string, cursor int) (io.ReadCloser, error)

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 (c *Client) ListJobArtifacts(ctx context.Context, jobID string, offset, limit int) ([]Artifact, error)

func (*Client) ListJobs

func (c *Client) ListJobs(ctx context.Context, status string, limit, offset int) (*JobList, error)

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 (c *Client) ListSessionFiles(ctx context.Context, sessionID, workspacePath string, recursive bool, limit int) (*WorkspaceListResult, error)

func (*Client) MkdirSessionDir

func (c *Client) MkdirSessionDir(ctx context.Context, sessionID, workspacePath string) (*WorkspaceFileInfo, error)

func (*Client) PatchSandbox

func (c *Client) PatchSandbox(ctx context.Context, sandboxID string, metadata map[string]string, resourceVersion int64) (*SandboxLease, error)

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) Release

func (c *Client) Release(ctx context.Context, sandboxID string) error

func (*Client) RemoveSessionFile

func (c *Client) RemoveSessionFile(ctx context.Context, sessionID, workspacePath string, recursive bool) error

func (*Client) Renew

func (c *Client) Renew(ctx context.Context, sandboxID string, extendSeconds int) (*SandboxLease, error)

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 (c *Client) StatSessionFile(ctx context.Context, sessionID, workspacePath string) (*WorkspaceFileInfo, error)

func (*Client) StopGUI

func (c *Client) StopGUI(ctx context.Context, sandboxID string) error

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) SubmitJob

func (c *Client) SubmitJob(ctx context.Context, req SubmitJobRequest) (*JobResult, error)

SubmitJob 提交 LRO job 并立即返回 queued/running 状态。

func (*Client) SubmitJobAndWait

func (c *Client) SubmitJobAndWait(ctx context.Context, req SubmitJobRequest, wait time.Duration) (*JobResult, error)

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 (c *Client) UploadJobFile(ctx context.Context, jobID string, name string, r io.Reader) (*Artifact, error)

func (*Client) UploadSessionFile

func (c *Client) UploadSessionFile(ctx context.Context, sessionID, workspacePath string, content io.Reader) (*WorkspaceFileInfo, error)

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) WaitJob

func (c *Client) WaitJob(ctx context.Context, jobID string) (*JobResult, error)

WaitJob 轮询现有 job,直到进入终态或 ctx 结束。

func (*Client) WaitJobWithOptions

func (c *Client) WaitJobWithOptions(ctx context.Context, jobID string, opts WaitJobOptions) (*JobResult, error)

func (*Client) WaitViewer

func (c *Client) WaitViewer(ctx context.Context, sandboxID string, opts WaitViewerOptions) (*ViewerDescriptor, error)

type Config

type Config struct {
	BaseURL        string
	Token          string
	Timeout        time.Duration
	HTTPClient     *http.Client
	MaxAttempts    int
	RetryBaseDelay time.Duration
	UserAgent      string
}

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 CreateWorkspaceRequest struct {
	WorkspaceID   string            `json:"workspace_id,omitempty"`
	RetentionMode string            `json:"retention_mode,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`
	TTLSeconds    int               `json:"ttl_seconds,omitempty"`
	QuotaMB       int               `json:"quota_mb,omitempty"`
}

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

func (h *ExecHandle) Events(ctx context.Context, cursor int) (*SSEStream, error)

Events opens an incrementally decoded SSE log stream. Caller must close it.

func (*ExecHandle) ID

func (h *ExecHandle) ID() string

ID returns the exec identifier.

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 ExecListQuery struct {
	Limit  int
	Cursor string
}

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.

func WithRecursive

func WithRecursive() FileOption

WithRecursive enables recursive file listing.

type JobList

type JobList struct {
	Items      []JobResult `json:"items"`
	NextOffset int         `json:"next_offset,omitempty"`
	Total      int         `json:"total"`
}

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 Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is an optional sink for non-fatal background diagnostics.

type Option

type Option func(*sandboxOptions)

Option is a functional option for New / QuickRun / RunBatch.

func WithEnv

func WithEnv(env map[string]string) Option

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

func WithHeartbeatInterval(d time.Duration) Option

WithHeartbeatInterval overrides the built-in heartbeat interval.

func WithHints

func WithHints(capabilities ...string) Option

WithHints provides capability hints for automatic profile selection.

func WithIdempotencyKey

func WithIdempotencyKey(key string) Option

WithIdempotencyKey sets the idempotency key for session creation.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger enables optional SDK diagnostics. The library is silent by default.

func WithMetadata

func WithMetadata(kv map[string]string) Option

WithMetadata attaches user metadata to the session/job request.

func WithProfile

func WithProfile(name string) Option

WithProfile sets an explicit profile name for environment selection.

func WithProfileRevision

func WithProfileRevision(name, revision string) Option

WithProfileRevision sets an explicit profile with a pinned revision.

func WithResolutionID

func WithResolutionID(id string) Option

WithResolutionID uses a pre-resolved environment ticket.

func WithSessionTTL

func WithSessionTTL(seconds int) Option

WithSessionTTL overrides the requested server-side session TTL in seconds.

func WithStrictHints

func WithStrictHints(capabilities ...string) Option

WithStrictHints sets strict capability hints (fail if not all satisfied).

func WithWorkspaceID

func WithWorkspaceID(workspaceID string) Option

WithWorkspaceID reuses an existing workspace instead of creating a new one.

func WithWorkspaceRetention

func WithWorkspaceRetention(mode string, ttlSeconds int) Option

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

type ProfileRef struct {
	Name     string `json:"name"`
	Revision string `json:"revision,omitempty"`
}

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

type SSEEvent struct {
	ID    string
	Event string
	Data  []byte
}

SSEEvent is one Server-Sent Event from a Job or Session exec log stream.

func (SSEEvent) DecodeJSON

func (e SSEEvent) DecodeJSON(target any) error

type SSEStream

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

SSEStream incrementally decodes an SSE response. Call Close when finished.

func (*SSEStream) Close

func (s *SSEStream) Close() error

func (*SSEStream) Next

func (s *SSEStream) Next() (*SSEEvent, error)

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

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

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) Close

func (sb *Sandbox) Close() error

func (*Sandbox) CloseContext

func (sb *Sandbox) CloseContext(ctx context.Context) error

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

func (sb *Sandbox) Download(ctx context.Context, path string) (io.ReadCloser, error)

Download reads a file from the workspace. If not yet opened, auto-triggers Open().

func (*Sandbox) Files

func (sb *Sandbox) Files(ctx context.Context, path string, opts ...FileOption) ([]FileEntry, error)

Files lists workspace directory entries. If not yet opened, auto-triggers Open().

func (*Sandbox) IsClosed

func (sb *Sandbox) IsClosed() bool

func (*Sandbox) IsOpen

func (sb *Sandbox) IsOpen() bool

IsOpen returns whether the Sandbox is in Session mode.

func (*Sandbox) Mkdir

func (sb *Sandbox) Mkdir(ctx context.Context, path string) error

Mkdir creates a directory tree in the workspace. If not yet opened, auto-triggers Open().

func (*Sandbox) Open

func (sb *Sandbox) Open(ctx context.Context) error

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

func (sb *Sandbox) Remove(ctx context.Context, path string, recursive bool) error

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

func (sb *Sandbox) RunNode(ctx context.Context, code string) (*ExecResult, error)

RunNode executes Node.js code (equivalent to Run(ctx, code, WithLang("javascript"))).

func (*Sandbox) RunPython

func (sb *Sandbox) RunPython(ctx context.Context, code string) (*ExecResult, error)

RunPython executes Python code (equivalent to Run(ctx, code, WithLang("python"))).

func (*Sandbox) RunShell

func (sb *Sandbox) RunShell(ctx context.Context, script string) (*ExecResult, error)

RunShell executes a shell script (equivalent to Run(ctx, script, WithLang("shell"))).

func (*Sandbox) SessionID

func (sb *Sandbox) SessionID() string

SessionID returns the session identifier (empty if not opened).

func (*Sandbox) SetCwd

func (sb *Sandbox) SetCwd(ctx context.Context, cwd string) error

SetCwd modifies the session-level working directory (Session mode only).

func (*Sandbox) SetEnv

func (sb *Sandbox) SetEnv(ctx context.Context, env map[string]string) error

SetEnv modifies the session-level environment variables (Session mode only).

func (*Sandbox) StatFile

func (sb *Sandbox) StatFile(ctx context.Context, path string) (*FileEntry, error)

StatFile returns metadata for a workspace file. If not yet opened, auto-triggers Open().

func (*Sandbox) Suspend

func (sb *Sandbox) Suspend(ctx context.Context) error

Suspend releases the runtime (container) while preserving the session workspace. Only available in Session mode.

func (*Sandbox) Upload

func (sb *Sandbox) Upload(ctx context.Context, path string, content io.Reader) error

Upload writes a file to the workspace. If not yet opened, auto-triggers Open() (transparent upgrade to Session mode).

func (*Sandbox) WorkspaceID

func (sb *Sandbox) WorkspaceID() string

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 SandboxMetadataPatch map[string]*string

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

type SessionContext struct {
	Cwd string            `json:"cwd"`
	Env map[string]string `json:"env,omitempty"`
}

SessionContext represents the mutable session-level cwd/env state.

type StartGUIRequest

type StartGUIRequest struct {
	Kind       string            `json:"kind,omitempty"`
	Resolution string            `json:"resolution,omitempty"`
	TTLSeconds int               `json:"ttl_seconds,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
}

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 WaitExecOptions struct {
	PollInterval time.Duration
}

type WaitJobOptions

type WaitJobOptions struct {
	PollInterval time.Duration
}

type WaitViewerOptions

type WaitViewerOptions struct {
	Kind         string
	PollInterval time.Duration
	Timeout      time.Duration
}

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"`
}

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.

Jump to

Keyboard shortcuts

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