An open-source, faster Devin alternative
TypeScript
checkpoints as templates
Brian Reardond8fda8e53342
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.gonew file mode 100644index 00000000..6a7c4d05--- /dev/null+++ b/internal/api/image_builder.go@@ -0,0 +1,605 @@+package api++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "log"+ "strings"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/storage"+ "github.com/opensandbox/opensandbox/pkg/types"+ pb "github.com/opensandbox/opensandbox/proto/worker"+)++// ImageManifest is the parsed declarative image definition from the SDK.+type ImageManifest struct {+ Base string `json:"base"`+ Steps []ImageStep `json:"steps"`+}++// ImageStep is a single build step in an image manifest.+type ImageStep struct {+ Type string `json:"type"`+ Args map[string]interface{} `json:"args"`+}++// BuildLogFunc is a callback for streaming build log messages.+// If nil, logs are only written to the server log.+type BuildLogFunc func(step int, stepType string, message string)++// in-flight image builds — prevents duplicate builds for same hash+var inflightBuilds sync.Map // map[string]*imageBuild++type imageBuild struct {+ ready chan struct{}+ checkpointID uuid.UUID+ err error+}++// computeManifestHash returns a deterministic SHA-256 hash for the manifest.+func computeManifestHash(manifest *ImageManifest) string {+ // Canonical JSON: marshal with sorted keys (Go's encoding/json sorts map keys)+ data, _ := json.Marshal(manifest)+ sum := sha256.Sum256(data)+ return hex.EncodeToString(sum[:])+}++// translateStepToCommand converts an image step to a shell command.+func translateStepToCommand(step ImageStep) (string, error) {+ switch step.Type {+ case "apt_install":+ pkgs, ok := step.Args["packages"]+ if !ok {+ return "", fmt.Errorf("apt_install: missing packages")+ }+ packages, err := toStringSlice(pkgs)+ if err != nil {+ return "", fmt.Errorf("apt_install: %w", err)+ }+ return fmt.Sprintf("DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq %s", strings.Join(packages, " ")), nil++ case "pip_install":+ pkgs, ok := step.Args["packages"]+ if !ok {+ return "", fmt.Errorf("pip_install: missing packages")+ }+ packages, err := toStringSlice(pkgs)+ if err != nil {+ return "", fmt.Errorf("pip_install: %w", err)+ }+ return fmt.Sprintf("pip install -q %s", strings.Join(packages, " ")), nil++ case "run":+ cmds, ok := step.Args["commands"]+ if !ok {+ return "", fmt.Errorf("run: missing commands")+ }+ commands, err := toStringSlice(cmds)+ if err != nil {+ return "", fmt.Errorf("run: %w", err)+ }+ return strings.Join(commands, " && "), nil++ case "env":+ vars, ok := step.Args["vars"]+ if !ok {+ return "", fmt.Errorf("env: missing vars")+ }+ varsMap, ok := vars.(map[string]interface{})+ if !ok {+ return "", fmt.Errorf("env: vars must be a map")+ }+ var parts []string+ for k, v := range varsMap {+ val := fmt.Sprintf("%v", v)+ // Write to /etc/environment for persistence across sessions+ parts = append(parts, fmt.Sprintf("echo '%s=%s' >> /etc/environment", k, val))+ // Also write to profile.d for interactive shells+ parts = append(parts, fmt.Sprintf("echo 'export %s=\"%s\"' >> /etc/profile.d/osb-image.sh", k, val))+ }+ return strings.Join(parts, " && "), nil++ case "workdir":+ path, ok := step.Args["path"]+ if !ok {+ return "", fmt.Errorf("workdir: missing path")+ }+ pathStr, ok := path.(string)+ if !ok {+ return "", fmt.Errorf("workdir: path must be a string")+ }+ return fmt.Sprintf("mkdir -p %s", pathStr), nil++ case "add_file":+ remotePath, ok := step.Args["path"]+ if !ok {+ return "", fmt.Errorf("add_file: missing path")+ }+ pathStr, ok := remotePath.(string)+ if !ok {+ return "", fmt.Errorf("add_file: path must be a string")+ }+ content, ok := step.Args["content"]+ if !ok {+ return "", fmt.Errorf("add_file: missing content")+ }+ contentStr, ok := content.(string)+ if !ok {+ return "", fmt.Errorf("add_file: content must be a string")+ }+ // Create parent directory and decode base64 content+ dir := pathStr[:strings.LastIndex(pathStr, "/")]+ return fmt.Sprintf("mkdir -p %s && echo '%s' | base64 -d > %s", dir, contentStr, pathStr), nil++ case "add_dir":+ remotePath, ok := step.Args["path"]+ if !ok {+ return "", fmt.Errorf("add_dir: missing path")+ }+ pathStr, ok := remotePath.(string)+ if !ok {+ return "", fmt.Errorf("add_dir: path must be a string")+ }+ filesRaw, ok := step.Args["files"]+ if !ok {+ return "", fmt.Errorf("add_dir: missing files")+ }+ filesArr, ok := filesRaw.([]interface{})+ if !ok {+ return "", fmt.Errorf("add_dir: files must be an array")+ }++ var parts []string+ parts = append(parts, fmt.Sprintf("mkdir -p %s", pathStr))+ for _, fileRaw := range filesArr {+ fileMap, ok := fileRaw.(map[string]interface{})+ if !ok {+ return "", fmt.Errorf("add_dir: each file must be an object")+ }+ relPath, _ := fileMap["relativePath"].(string)+ fileContent, _ := fileMap["content"].(string)+ if relPath == "" || fileContent == "" {+ continue+ }+ fullPath := pathStr + "/" + relPath+ dir := fullPath[:strings.LastIndex(fullPath, "/")]+ parts = append(parts, fmt.Sprintf("mkdir -p %s && echo '%s' | base64 -d > %s", dir, fileContent, fullPath))+ }+ return strings.Join(parts, " && "), nil++ default:+ return "", fmt.Errorf("unknown step type: %s", step.Type)+ }+}++// toStringSlice converts an interface{} (expected []interface{}) to []string.+func toStringSlice(v interface{}) ([]string, error) {+ arr, ok := v.([]interface{})+ if !ok {+ return nil, fmt.Errorf("expected array, got %T", v)+ }+ result := make([]string, len(arr))+ for i, item := range arr {+ s, ok := item.(string)+ if !ok {+ return nil, fmt.Errorf("expected string at index %d, got %T", i, item)+ }+ result[i] = s+ }+ return result, nil+}++// resolveImageManifest handles image-based sandbox creation.+// Returns the checkpoint ID to create from, or an error.+// If the image is already cached, returns immediately.+// Otherwise, builds it synchronously (boots sandbox, runs steps, checkpoints).+// The optional logFn callback is called for each build step with progress info.+func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, manifestJSON json.RawMessage, logFn BuildLogFunc) (uuid.UUID, error) {+ var manifest ImageManifest+ if err := json.Unmarshal(manifestJSON, &manifest); err != nil {+ return uuid.Nil, fmt.Errorf("invalid image manifest: %w", err)+ }++ contentHash := computeManifestHash(&manifest)++ // 1. Check DB cache+ if s.store != nil {+ cached, err := s.store.GetImageCacheByHash(ctx, orgID, contentHash)+ if err == nil && cached.Status == "ready" && cached.CheckpointID != nil {+ // Cache hit — update last_used_at and return+ _ = s.store.TouchImageCacheUsage(ctx, cached.ID)+ log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)+ if logFn != nil {+ logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))+ }+ return *cached.CheckpointID, nil+ }+ if err == nil && cached.Status == "building" {+ // Another request is building this same image — wait for it+ return s.waitForInflightBuild(contentHash)+ }+ }++ // 2. Check in-flight builds (race between DB check and build start)+ buildKey := fmt.Sprintf("%s:%s", orgID, contentHash)+ if existing, loaded := inflightBuilds.Load(buildKey); loaded {+ build := existing.(*imageBuild)+ select {+ case <-build.ready:+ if build.err != nil {+ return uuid.Nil, build.err+ }+ return build.checkpointID, nil+ case <-ctx.Done():+ return uuid.Nil, ctx.Err()+ }+ }++ // 3. Start building+ build := &imageBuild{ready: make(chan struct{})}+ if _, loaded := inflightBuilds.LoadOrStore(buildKey, build); loaded {+ // Lost the race — another goroutine started building+ existing, _ := inflightBuilds.Load(buildKey)+ build = existing.(*imageBuild)+ select {+ case <-build.ready:+ if build.err != nil {+ return uuid.Nil, build.err+ }+ return build.checkpointID, nil+ case <-ctx.Done():+ return uuid.Nil, ctx.Err()+ }+ }++ // We own the build+ defer func() {+ close(build.ready)+ inflightBuilds.Delete(buildKey)+ }()++ // Create DB record+ cacheID := uuid.New()+ if s.store != nil {+ ic := &db.ImageCache{+ ID: cacheID,+ OrgID: orgID,+ ContentHash: contentHash,+ Manifest: manifestJSON,+ Status: "building",+ }+ if err := s.store.CreateImageCache(ctx, ic); err != nil {+ // Might conflict with concurrent insert — try to read existing+ cached, readErr := s.store.GetImageCacheByHash(ctx, orgID, contentHash)+ if readErr == nil && cached.Status == "ready" && cached.CheckpointID != nil {+ build.checkpointID = *cached.CheckpointID+ return build.checkpointID, nil+ }+ log.Printf("image-builder: cache insert failed (non-fatal): %v", err)+ }+ }++ // Build the image+ checkpointID, err := s.buildImage(ctx, orgID, &manifest, logFn)+ if err != nil {+ build.err = err+ if s.store != nil {+ _ = s.store.SetImageCacheFailed(ctx, cacheID)+ }+ return uuid.Nil, fmt.Errorf("image build failed: %w", err)+ }++ // Mark cache as ready+ build.checkpointID = checkpointID+ if s.store != nil {+ _ = s.store.SetImageCacheReady(ctx, cacheID, checkpointID)+ }++ log.Printf("image-builder: built image hash=%s checkpoint=%s (%d steps)", contentHash[:12], checkpointID, len(manifest.Steps))+ return checkpointID, nil+}++// waitForInflightBuild waits for an existing in-flight build to complete.+func (s *Server) waitForInflightBuild(contentHash string) (uuid.UUID, error) {+ // Poll DB until status changes (simple approach — builds are typically 30-120s)+ for i := 0; i < 120; i++ {+ time.Sleep(1 * time.Second)+ // We can't easily wait on the in-flight build from another request+ // so just poll the DB status+ }+ return uuid.Nil, fmt.Errorf("timed out waiting for image build (hash=%s)", contentHash[:12])+}++// buildImage boots a throwaway sandbox, runs the manifest steps, and creates a checkpoint.+func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *ImageManifest, logFn BuildLogFunc) (uuid.UUID, error) {+ // Determine base template — normalize common aliases to "base"+ base := manifest.Base+ if base == "" || base == "ubuntu" || base == "default" {+ base = "base"+ }++ // Create a throwaway sandbox+ buildSandboxID := "sb-build-" + uuid.New().String()[:8]+ cfg := types.SandboxConfig{+ Template: base,+ Timeout: 600, // 10 min max for builds+ SandboxID: buildSandboxID,+ }++ log.Printf("image-builder: creating build sandbox %s (base=%s, steps=%d)", buildSandboxID, base, len(manifest.Steps))++ var grpcClient pb.SandboxWorkerClient+ var workerID string++ if s.workerRegistry != nil {+ region := s.region+ if region == "" {+ region = "iad"+ }+ worker, client, err := s.workerRegistry.GetLeastLoadedWorker(region)+ if err != nil {+ return uuid.Nil, fmt.Errorf("no workers available: %w", err)+ }+ grpcClient = client+ workerID = worker.ID++ // Create sandbox on worker+ createCtx, cancel := context.WithTimeout(ctx, 60*time.Second)+ defer cancel()++ resp, err := grpcClient.CreateSandbox(createCtx, &pb.CreateSandboxRequest{+ Template: cfg.Template,+ Timeout: int32(cfg.Timeout),+ NetworkEnabled: true, // Need network for apt/pip+ SandboxId: buildSandboxID,+ })+ if err != nil {+ return uuid.Nil, fmt.Errorf("failed to create build sandbox: %w", err)+ }+ _ = resp+ } else if s.manager != nil {+ cfg.NetworkEnabled = true+ sb, err := s.manager.Create(ctx, cfg)+ if err != nil {+ return uuid.Nil, fmt.Errorf("failed to create build sandbox: %w", err)+ }+ buildSandboxID = sb.ID+ workerID = s.workerID+ } else {+ return uuid.Nil, fmt.Errorf("no execution backend available")+ }++ // Cleanup: always destroy the build sandbox and mark it stopped in PG+ defer func() {+ cleanCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if grpcClient != nil {+ _, _ = grpcClient.DestroySandbox(cleanCtx, &pb.DestroySandboxRequest{SandboxId: buildSandboxID})+ } else if s.manager != nil {+ _ = s.manager.Kill(cleanCtx, buildSandboxID)+ }+ if s.store != nil {+ _ = s.store.UpdateSandboxSessionStatus(cleanCtx, buildSandboxID, "stopped", nil)+ }+ log.Printf("image-builder: destroyed build sandbox %s", buildSandboxID)+ }()++ // Record session in PG (so worker can find it)+ if s.store != nil {+ cfgJSON, _ := json.Marshal(cfg)+ region := s.region+ if region == "" {+ region = "local"+ }+ if workerID == "" {+ workerID = "w-local-1"+ }+ _, _ = s.store.CreateSandboxSession(ctx, buildSandboxID, orgID, nil, cfg.Template, region, workerID, cfgJSON, []byte("{}"))+ }++ // Emit build start log+ if logFn != nil {+ logFn(0, "build", fmt.Sprintf("Building image with %d steps (sandbox=%s)", len(manifest.Steps), buildSandboxID))+ }++ // Execute each step+ for i, step := range manifest.Steps {+ cmd, err := translateStepToCommand(step)+ if err != nil {+ return uuid.Nil, fmt.Errorf("step %d (%s): %w", i, step.Type, err)+ }++ log.Printf("image-builder: [%s] step %d/%d: %s → %s", buildSandboxID, i+1, len(manifest.Steps), step.Type, truncate(cmd, 80))+ if logFn != nil {+ logFn(i+1, step.Type, fmt.Sprintf("Step %d/%d: %s", i+1, len(manifest.Steps), stepDescription(step)))+ }++ if err := s.execBuildStep(ctx, grpcClient, buildSandboxID, i, step.Type, cmd); err != nil {+ return uuid.Nil, err+ }++ if logFn != nil {+ logFn(i+1, step.Type, fmt.Sprintf("Step %d/%d completed", i+1, len(manifest.Steps)))+ }+ }++ if logFn != nil {+ logFn(len(manifest.Steps)+1, "checkpoint", "Creating checkpoint...")+ }++ // Checkpoint the build sandbox+ checkpointID := uuid.New()++ log.Printf("image-builder: checkpointing build sandbox %s as %s", buildSandboxID, checkpointID)++ // Create checkpoint record in DB+ if s.store != nil {+ cfgJSON, _ := json.Marshal(cfg)+ cp := &db.Checkpoint{+ ID: checkpointID,+ SandboxID: buildSandboxID,+ OrgID: orgID,+ Name: fmt.Sprintf("_image_build_%s", checkpointID.String()[:8]),+ SandboxConfig: cfgJSON,+ }+ if err := s.store.CreateCheckpoint(ctx, cp); err != nil {+ return uuid.Nil, fmt.Errorf("failed to create checkpoint record: %w", err)+ }+ }++ // Create checkpoint on worker+ if grpcClient != nil {+ cpCtx, cancel := context.WithTimeout(ctx, 120*time.Second)+ defer cancel()++ resp, err := grpcClient.CreateCheckpoint(cpCtx, &pb.CreateCheckpointRequest{+ SandboxId: buildSandboxID,+ CheckpointId: checkpointID.String(),+ })+ if err != nil {+ return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)+ }++ // Update checkpoint with S3 keys+ if s.store != nil {+ _ = s.store.SetCheckpointReady(ctx, checkpointID, resp.RootfsS3Key, resp.WorkspaceS3Key, 0)+ }+ } else if s.manager != nil {+ // Combined mode: call CreateCheckpoint via reflection-free approach.+ // The concrete firecracker.Manager implements CreateCheckpoint directly.+ type checkpointer interface {+ CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (string, string, error)+ }+ cpMgr, ok := s.manager.(checkpointer)+ if !ok {+ return uuid.Nil, fmt.Errorf("manager does not support checkpoints")+ }++ rootfsKey, workspaceKey, err := cpMgr.CreateCheckpoint(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, func() {})+ if err != nil {+ return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)+ }++ if s.store != nil {+ _ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, 0)+ }+ }++ return checkpointID, nil+}++// resolveSnapshot looks up a named snapshot and returns its checkpoint ID.+func (s *Server) resolveSnapshot(ctx context.Context, orgID uuid.UUID, snapshotName string) (uuid.UUID, error) {+ if s.store == nil {+ return uuid.Nil, fmt.Errorf("database not configured")+ }++ cached, err := s.store.GetImageCacheByName(ctx, orgID, snapshotName)+ if err != nil {+ return uuid.Nil, fmt.Errorf("snapshot %q not found: %w", snapshotName, err)+ }++ if cached.Status != "ready" {+ return uuid.Nil, fmt.Errorf("snapshot %q is not ready (status: %s)", snapshotName, cached.Status)+ }++ if cached.CheckpointID == nil {+ return uuid.Nil, fmt.Errorf("snapshot %q has no checkpoint", snapshotName)+ }++ _ = s.store.TouchImageCacheUsage(ctx, cached.ID)+ return *cached.CheckpointID, nil+}++// execBuildStep runs a single build step command on the sandbox.+func (s *Server) execBuildStep(ctx context.Context, grpcClient pb.SandboxWorkerClient, sandboxID string, stepIdx int, stepType, cmd string) error {+ execCtx, cancel := context.WithTimeout(ctx, 300*time.Second)+ defer cancel()++ if grpcClient != nil {+ resp, err := grpcClient.ExecCommand(execCtx, &pb.ExecCommandRequest{+ SandboxId: sandboxID,+ Command: cmd,+ Timeout: 300,+ })+ if err != nil {+ return fmt.Errorf("step %d (%s) exec failed: %w", stepIdx, stepType, err)+ }+ if resp.ExitCode != 0 {+ return fmt.Errorf("step %d (%s) failed (exit %d): %s", stepIdx, stepType, resp.ExitCode, truncate(resp.Stderr, 500))+ }+ } else if s.manager != nil {+ result, err := s.manager.Exec(execCtx, sandboxID, types.ProcessConfig{+ Command: cmd,+ Timeout: 300,+ })+ if err != nil {+ return fmt.Errorf("step %d (%s) exec failed: %w", stepIdx, stepType, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("step %d (%s) failed (exit %d): %s", stepIdx, stepType, result.ExitCode, truncate(result.Stderr, 500))+ }+ }+ return nil+}++func truncate(s string, maxLen int) string {+ if len(s) <= maxLen {+ return s+ }+ return s[:maxLen] + "..."+}++// stepDescription returns a human-readable description of a build step.+func stepDescription(step ImageStep) string {+ switch step.Type {+ case "apt_install":+ if pkgs, ok := step.Args["packages"]; ok {+ if arr, err := toStringSlice(pkgs); err == nil {+ return fmt.Sprintf("apt-get install %s", strings.Join(arr, " "))+ }+ }+ return "apt-get install"+ case "pip_install":+ if pkgs, ok := step.Args["packages"]; ok {+ if arr, err := toStringSlice(pkgs); err == nil {+ return fmt.Sprintf("pip install %s", strings.Join(arr, " "))+ }+ }+ return "pip install"+ case "run":+ if cmds, ok := step.Args["commands"]; ok {+ if arr, err := toStringSlice(cmds); err == nil {+ return truncate(strings.Join(arr, " && "), 120)+ }+ }+ return "run commands"+ case "env":+ return "set environment variables"+ case "workdir":+ if p, ok := step.Args["path"].(string); ok {+ return fmt.Sprintf("set workdir %s", p)+ }+ return "set workdir"+ case "add_file":+ if p, ok := step.Args["path"].(string); ok {+ return fmt.Sprintf("add file %s", p)+ }+ return "add file"+ case "add_dir":+ if p, ok := step.Args["path"].(string); ok {+ return fmt.Sprintf("add directory %s", p)+ }+ return "add directory"+ default:+ return step.Type+ }+}+diff --git a/internal/api/router.go b/internal/api/router.goindex 2251944e..88188ac1 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -175,6 +175,12 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.DELETE("/templates/:name", s.deleteTemplate)api.POST("/sandboxes/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)+ // Snapshots (pre-built declarative images)+ api.POST("/snapshots", s.createSnapshot)+ api.GET("/snapshots", s.listSnapshots)+ api.GET("/snapshots/:name", s.getSnapshot)+ api.DELETE("/snapshots/:name", s.deleteSnapshot)+// Workers (server mode only — queries worker registry)api.GET("/workers", s.listWorkers)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex c6e9b64a..5d0397d7 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -60,6 +60,37 @@ func (s *Server) createSandbox(c echo.Context) error {}}+ // Declarative image or named snapshot → resolve to checkpoint and use createFromCheckpoint flow+ if len(cfg.ImageManifest) > 0 || cfg.Snapshot != "" {+ if !hasOrg {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required for image/snapshot creation"})+ }++ // Check if the client wants build log streaming (SSE)+ wantsSSE := c.Request().Header.Get("Accept") == "text/event-stream"++ if wantsSSE {+ return s.createSandboxWithSSE(c, ctx, orgID, cfg)+ }++ // Non-streaming path+ var checkpointID uuid.UUID+ var err error++ if cfg.Snapshot != "" {+ checkpointID, err = s.resolveSnapshot(ctx, orgID, cfg.Snapshot)+ } else {+ checkpointID, err = s.resolveImageManifest(ctx, orgID, cfg.ImageManifest, nil)+ }+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ return s.createFromCheckpoint(c)+ }+// Server mode with worker registry: dispatch to remote worker via gRPCif s.workerRegistry != nil {return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)@@ -127,6 +158,67 @@ func (s *Server) createSandbox(c echo.Context) error {return c.JSON(http.StatusCreated, sb)}+// createSandboxWithSSE handles sandbox creation with SSE build log streaming.+// Streams build_log events during image build, then emits the final result event.+func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID uuid.UUID, cfg types.SandboxConfig) error {+ flusher, ok := c.Response().Writer.(http.Flusher)+ if !ok {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "streaming not supported"})+ }++ // Set SSE headers+ c.Response().Header().Set("Content-Type", "text/event-stream")+ c.Response().Header().Set("Cache-Control", "no-cache")+ c.Response().Header().Set("Connection", "keep-alive")+ c.Response().WriteHeader(http.StatusOK)+ flusher.Flush()++ // Helper to emit SSE events+ emit := func(eventType string, payload interface{}) {+ data, _ := json.Marshal(payload)+ fmt.Fprintf(c.Response(), "event: %s\ndata: %s\n\n", eventType, data)+ flusher.Flush()+ }++ // Build log callback — emits SSE events during image build+ logFn := BuildLogFunc(func(step int, stepType string, message string) {+ emit("build_log", map[string]interface{}{+ "step": step,+ "type": stepType,+ "message": message,+ })+ })++ // Resolve image or snapshot to checkpoint ID+ var checkpointID uuid.UUID+ var err error++ if cfg.Snapshot != "" {+ emit("build_log", map[string]interface{}{"step": 0, "type": "resolve", "message": "Resolving snapshot '" + cfg.Snapshot + "'..."})+ checkpointID, err = s.resolveSnapshot(ctx, orgID, cfg.Snapshot)+ } else {+ checkpointID, err = s.resolveImageManifest(ctx, orgID, cfg.ImageManifest, logFn)+ }+ if err != nil {+ emit("error", map[string]string{"error": err.Error()})+ return nil+ }++ // Create sandbox from checkpoint+ emit("build_log", map[string]interface{}{"step": 0, "type": "create", "message": "Creating sandbox from image..."})++ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ result, _, cpErr := s.createFromCheckpointCore(c)+ if cpErr != nil {+ emit("error", map[string]string{"error": cpErr.Error()})+ return nil+ }++ emit("result", result)+ return nil+}+// createSandboxRemote dispatches sandbox creation to a remote worker via gRPC.func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool) error {// Select region (explicit header, or default to server's region)@@ -995,33 +1087,43 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {// createFromCheckpoint creates a new sandbox from an existing checkpoint (fork).func (s *Server) createFromCheckpoint(c echo.Context) error {+ result, httpStatus, err := s.createFromCheckpointCore(c)+ if err != nil {+ return c.JSON(httpStatus, map[string]string{"error": err.Error()})+ }+ return c.JSON(httpStatus, result)+}++// createFromCheckpointCore contains the core logic for creating a sandbox from a checkpoint.+// Returns the result map, HTTP status, or an error.+func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{}, int, error) {checkpointIDStr := c.Param("checkpointId")ctx := c.Request().Context()if s.store == nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ return nil, http.StatusServiceUnavailable, fmt.Errorf("database not configured")}orgID, ok := auth.GetOrgID(c)if !ok {- return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ return nil, http.StatusUnauthorized, fmt.Errorf("org context required")}checkpointID, err := uuid.Parse(checkpointIDStr)if err != nil {- return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ return nil, http.StatusBadRequest, fmt.Errorf("invalid checkpoint ID")}// Verify checkpoint exists, belongs to org, and is readycp, err := s.store.GetCheckpoint(ctx, checkpointID)if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ return nil, http.StatusNotFound, fmt.Errorf("checkpoint not found")}if cp.OrgID != orgID {- return c.JSON(http.StatusForbidden, map[string]string{"error": "checkpoint does not belong to this organization"})+ return nil, http.StatusForbidden, fmt.Errorf("checkpoint does not belong to this organization")}if cp.Status != "ready" {- return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready (status: " + cp.Status + ")"})+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint is not ready (status: %s)", cp.Status)}// Parse optional overrides from request body@@ -1032,7 +1134,7 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {// Get S3 keys from the checkpointif cp.RootfsS3Key == nil || cp.WorkspaceS3Key == nil {- return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint S3 keys not available"})+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint S3 keys not available")}// Parse the original sandbox config to reuse settings@@ -1063,9 +1165,9 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {if s.workerRegistry != nil {// Server mode: pick a worker- worker, client, err := s.workerRegistry.GetLeastLoadedWorker(region)- if err != nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "no workers available: " + err.Error()})+ worker, client, wErr := s.workerRegistry.GetLeastLoadedWorker(region)+ if wErr != nil {+ return nil, http.StatusServiceUnavailable, fmt.Errorf("no workers available: %w", wErr)}workerID = worker.IDgrpcClient = client@@ -1073,7 +1175,7 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {// Combined mode: local executionworkerID = s.workerID} else {- return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ return nil, http.StatusServiceUnavailable, fmt.Errorf("sandbox execution not available in server-only mode")}// Register pending create — commands will wait until ready@@ -1088,8 +1190,8 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {// Issue JWT immediatelyvar token stringif s.jwtIssuer != nil {- t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 24*time.Hour)- if err == nil {+ t, jwtErr := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 24*time.Hour)+ if jwtErr == nil {token = t}}@@ -1166,14 +1268,14 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {}}()- return c.JSON(http.StatusCreated, map[string]interface{}{+ return map[string]interface{}{"sandboxID": sandboxID,"status": "creating","token": token,"region": region,"workerID": workerID,"fromCheckpointId": checkpointID.String(),- })+ }, http.StatusCreated, nil}// deleteCheckpoint deletes a checkpoint.diff --git a/internal/api/snapshots.go b/internal/api/snapshots.gonew file mode 100644index 00000000..e684f4d0--- /dev/null+++ b/internal/api/snapshots.go@@ -0,0 +1,218 @@+package api++import (+ "context"+ "encoding/json"+ "fmt"+ "log"+ "net/http"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+)++// createSnapshot handles POST /api/snapshots — creates a pre-built named snapshot from a declarative image.+func (s *Server) createSnapshot(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ var req struct {+ Name string `json:"name"`+ Image json.RawMessage `json:"image"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }++ if req.Name == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})+ }+ if len(req.Image) == 0 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "image is required"})+ }++ ctx := c.Request().Context()++ // Check if name is already taken+ existing, err := s.store.GetImageCacheByName(ctx, orgID, req.Name)+ if err == nil && existing != nil {+ return c.JSON(http.StatusConflict, map[string]string{"error": "snapshot name already exists"})+ }++ // SSE streaming path+ if c.Request().Header.Get("Accept") == "text/event-stream" {+ return s.createSnapshotWithSSE(c, ctx, orgID, req.Name, req.Image)+ }++ // Non-streaming path+ ic, err := s.createSnapshotCore(ctx, orgID, req.Name, req.Image, nil)+ if err != nil {+ log.Printf("snapshot: build failed for %q: %v", req.Name, err)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ log.Printf("snapshot: created %q", req.Name)+ return c.JSON(http.StatusCreated, ic)+}++// createSnapshotCore contains the shared snapshot creation logic.+func (s *Server) createSnapshotCore(ctx context.Context, orgID uuid.UUID, name string, imageJSON json.RawMessage, logFn BuildLogFunc) (*db.ImageCache, error) {+ checkpointID, err := s.resolveImageManifest(ctx, orgID, imageJSON, logFn)+ if err != nil {+ return nil, fmt.Errorf("image build failed: %w", err)+ }++ // Parse manifest for hash computation+ var manifest ImageManifest+ _ = json.Unmarshal(imageJSON, &manifest)+ contentHash := computeManifestHash(&manifest)++ // Check if an unnamed cache entry already exists with this hash — if so, just name it+ cached, err := s.store.GetImageCacheByHash(ctx, orgID, contentHash)+ if err == nil && cached.Name == nil {+ n := name+ ic := &db.ImageCache{+ ID: uuid.New(),+ OrgID: orgID,+ ContentHash: contentHash + ":named:" + name,+ CheckpointID: &checkpointID,+ Name: &n,+ Manifest: imageJSON,+ Status: "ready",+ }+ if createErr := s.store.CreateImageCache(ctx, ic); createErr != nil {+ return nil, fmt.Errorf("failed to save snapshot: %w", createErr)+ }+ return ic, nil+ }++ // Create a new named entry+ n := name+ ic := &db.ImageCache{+ ID: uuid.New(),+ OrgID: orgID,+ ContentHash: contentHash,+ CheckpointID: &checkpointID,+ Name: &n,+ Manifest: imageJSON,+ Status: "ready",+ }+ if createErr := s.store.CreateImageCache(ctx, ic); createErr != nil {+ // Might already exist from the resolveImageManifest call+ existing, readErr := s.store.GetImageCacheByHash(ctx, orgID, contentHash)+ if readErr == nil {+ return existing, nil+ }+ return nil, fmt.Errorf("failed to save snapshot: %w", createErr)+ }++ log.Printf("snapshot: created %q (checkpoint=%s)", name, checkpointID)+ return ic, nil+}++// createSnapshotWithSSE handles snapshot creation with SSE build log streaming.+func (s *Server) createSnapshotWithSSE(c echo.Context, ctx context.Context, orgID uuid.UUID, name string, imageJSON json.RawMessage) error {+ flusher, ok := c.Response().Writer.(http.Flusher)+ if !ok {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "streaming not supported"})+ }++ c.Response().Header().Set("Content-Type", "text/event-stream")+ c.Response().Header().Set("Cache-Control", "no-cache")+ c.Response().Header().Set("Connection", "keep-alive")+ c.Response().WriteHeader(http.StatusOK)+ flusher.Flush()++ emit := func(eventType string, payload interface{}) {+ data, _ := json.Marshal(payload)+ fmt.Fprintf(c.Response(), "event: %s\ndata: %s\n\n", eventType, data)+ flusher.Flush()+ }++ logFn := BuildLogFunc(func(step int, stepType string, message string) {+ emit("build_log", map[string]interface{}{+ "step": step,+ "type": stepType,+ "message": message,+ })+ })++ ic, err := s.createSnapshotCore(ctx, orgID, name, imageJSON, logFn)+ if err != nil {+ emit("error", map[string]string{"error": err.Error()})+ return nil+ }++ emit("result", ic)+ return nil+}++// listSnapshots handles GET /api/snapshots — lists all named snapshots for the org.+func (s *Server) listSnapshots(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ snapshots, err := s.store.ListImageCacheByOrg(c.Request().Context(), orgID, true)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ if snapshots == nil {+ snapshots = []db.ImageCache{}+ }++ return c.JSON(http.StatusOK, snapshots)+}++// getSnapshot handles GET /api/snapshots/:name — gets a snapshot by name.+func (s *Server) getSnapshot(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ name := c.Param("name")+ snapshot, err := s.store.GetImageCacheByName(c.Request().Context(), orgID, name)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "snapshot not found"})+ }++ return c.JSON(http.StatusOK, snapshot)+}++// deleteSnapshot handles DELETE /api/snapshots/:name — deletes a named snapshot.+func (s *Server) deleteSnapshot(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ name := c.Param("name")+ if err := s.store.DeleteImageCacheByName(c.Request().Context(), orgID, name); err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ return c.NoContent(http.StatusNoContent)+}diff --git a/internal/db/migrations/014_image_cache.down.sql b/internal/db/migrations/014_image_cache.down.sqlnew file mode 100644index 00000000..4f66e664--- /dev/null+++ b/internal/db/migrations/014_image_cache.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS image_cache;diff --git a/internal/db/migrations/014_image_cache.up.sql b/internal/db/migrations/014_image_cache.up.sqlnew file mode 100644index 00000000..86157f07--- /dev/null+++ b/internal/db/migrations/014_image_cache.up.sql@@ -0,0 +1,22 @@+-- Image cache: maps content-hashed image manifests to checkpoints.+-- Named entries are "snapshots" (persistent, user-facing); unnamed are auto-cached.+CREATE TABLE image_cache (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ org_id UUID NOT NULL REFERENCES orgs(id),+ content_hash TEXT NOT NULL,+ checkpoint_id UUID REFERENCES sandbox_checkpoints(id) ON DELETE SET NULL,+ name TEXT, -- NULL for auto-cached; unique per org when set+ manifest JSONB NOT NULL DEFAULT '{}',+ status TEXT NOT NULL DEFAULT 'building', -- building | ready | failed+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_used_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Only one entry per (org, content_hash)+CREATE UNIQUE INDEX idx_image_cache_org_hash ON image_cache(org_id, content_hash);++-- Named snapshots are unique per org+CREATE UNIQUE INDEX idx_image_cache_org_name ON image_cache(org_id, name) WHERE name IS NOT NULL;++-- Fast lookup by checkpoint+CREATE INDEX idx_image_cache_checkpoint ON image_cache(checkpoint_id);diff --git a/internal/db/store.go b/internal/db/store.goindex 28a7aa2b..191af158 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -77,6 +77,7 @@ func (s *Store) Migrate(ctx context.Context) error {{11, "migrations/011_rename_hibernation.up.sql"},{12, "migrations/012_checkpoints.up.sql"},{13, "migrations/013_checkpoint_patches.up.sql"},+ {14, "migrations/014_image_cache.up.sql"},}for _, m := range migrations {@@ -1147,6 +1148,133 @@ func (s *Store) DeleteTemplateForOrg(ctx context.Context, id uuid.UUID, orgID uureturn nil}+// --- Image Cache operations ---++// ImageCache represents a cached image build (content-hashed manifest → checkpoint).+type ImageCache struct {+ ID uuid.UUID `json:"id"`+ OrgID uuid.UUID `json:"orgId"`+ ContentHash string `json:"contentHash"`+ CheckpointID *uuid.UUID `json:"checkpointId,omitempty"`+ Name *string `json:"name,omitempty"` // nil for auto-cached, set for named snapshots+ Manifest json.RawMessage `json:"manifest"`+ Status string `json:"status"` // building | ready | failed+ CreatedAt time.Time `json:"createdAt"`+ LastUsedAt time.Time `json:"lastUsedAt"`+}++// GetImageCacheByHash looks up a cached image by org + content hash.+func (s *Store) GetImageCacheByHash(ctx context.Context, orgID uuid.UUID, contentHash string) (*ImageCache, error) {+ ic := &ImageCache{}+ err := s.pool.QueryRow(ctx,+ `SELECT id, org_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at+ FROM image_cache WHERE org_id = $1 AND content_hash = $2`,+ orgID, contentHash,+ ).Scan(&ic.ID, &ic.OrgID, &ic.ContentHash, &ic.CheckpointID, &ic.Name, &ic.Manifest, &ic.Status, &ic.CreatedAt, &ic.LastUsedAt)+ if err != nil {+ return nil, fmt.Errorf("image cache not found: %w", err)+ }+ return ic, nil+}++// GetImageCacheByName looks up a named snapshot by org + name.+func (s *Store) GetImageCacheByName(ctx context.Context, orgID uuid.UUID, name string) (*ImageCache, error) {+ ic := &ImageCache{}+ err := s.pool.QueryRow(ctx,+ `SELECT id, org_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at+ FROM image_cache WHERE org_id = $1 AND name = $2`,+ orgID, name,+ ).Scan(&ic.ID, &ic.OrgID, &ic.ContentHash, &ic.CheckpointID, &ic.Name, &ic.Manifest, &ic.Status, &ic.CreatedAt, &ic.LastUsedAt)+ if err != nil {+ return nil, fmt.Errorf("snapshot %q not found: %w", name, err)+ }+ return ic, nil+}++// CreateImageCache inserts a new image cache record.+func (s *Store) CreateImageCache(ctx context.Context, ic *ImageCache) error {+ return s.pool.QueryRow(ctx,+ `INSERT INTO image_cache (id, org_id, content_hash, checkpoint_id, name, manifest, status)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ RETURNING created_at, last_used_at`,+ ic.ID, ic.OrgID, ic.ContentHash, ic.CheckpointID, ic.Name, ic.Manifest, ic.Status,+ ).Scan(&ic.CreatedAt, &ic.LastUsedAt)+}++// SetImageCacheReady marks an image cache entry as ready with its checkpoint ID.+func (s *Store) SetImageCacheReady(ctx context.Context, id uuid.UUID, checkpointID uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE image_cache SET status = 'ready', checkpoint_id = $2, last_used_at = now() WHERE id = $1`,+ id, checkpointID)+ return err+}++// SetImageCacheFailed marks an image cache entry as failed.+func (s *Store) SetImageCacheFailed(ctx context.Context, id uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE image_cache SET status = 'failed' WHERE id = $1`, id)+ return err+}++// TouchImageCacheUsage updates the last_used_at timestamp.+func (s *Store) TouchImageCacheUsage(ctx context.Context, id uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE image_cache SET last_used_at = now() WHERE id = $1`, id)+ return err+}++// ListImageCacheByOrg returns all image cache entries for an org, newest first.+func (s *Store) ListImageCacheByOrg(ctx context.Context, orgID uuid.UUID, namedOnly bool) ([]ImageCache, error) {+ query := `SELECT id, org_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at+ FROM image_cache WHERE org_id = $1`+ if namedOnly {+ query += ` AND name IS NOT NULL`+ }+ query += ` ORDER BY created_at DESC`++ rows, err := s.pool.Query(ctx, query, orgID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var results []ImageCache+ for rows.Next() {+ var ic ImageCache+ if err := rows.Scan(&ic.ID, &ic.OrgID, &ic.ContentHash, &ic.CheckpointID, &ic.Name, &ic.Manifest, &ic.Status, &ic.CreatedAt, &ic.LastUsedAt); err != nil {+ return nil, err+ }+ results = append(results, ic)+ }+ return results, rows.Err()+}++// DeleteImageCache deletes an image cache entry by ID (org-scoped).+func (s *Store) DeleteImageCache(ctx context.Context, orgID uuid.UUID, id uuid.UUID) error {+ tag, err := s.pool.Exec(ctx,+ `DELETE FROM image_cache WHERE id = $1 AND org_id = $2`, id, orgID)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("image cache entry not found or not owned by org")+ }+ return nil+}++// DeleteImageCacheByName deletes a named snapshot by org + name.+func (s *Store) DeleteImageCacheByName(ctx context.Context, orgID uuid.UUID, name string) error {+ tag, err := s.pool.Exec(ctx,+ `DELETE FROM image_cache WHERE org_id = $1 AND name = $2`, orgID, name)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("snapshot %q not found", name)+ }+ return nil+}+// --- Preview URL operations ---// PreviewURL represents an on-demand preview URL for a sandbox.diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex 9f3ad16a..a64be3af 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -1,6 +1,9 @@package types-import "time"+import (+ "encoding/json"+ "time"+)// SandboxStatus represents the current state of a sandbox.type SandboxStatus string@@ -46,6 +49,12 @@ type SandboxConfig struct {// When set, the sandbox boots from these drives instead of the standard base image.TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`TemplateWorkspaceKey string `json:"templateWorkspaceKey,omitempty"`+ // Declarative image manifest: when set, the server builds and caches+ // the image as a checkpoint before creating the sandbox.+ ImageManifest json.RawMessage `json:"image,omitempty"`+ // Snapshot name: when set, the server resolves a named snapshot (image cache)+ // and creates the sandbox from its cached checkpoint.+ Snapshot string `json:"snapshot,omitempty"`// SandboxID allows pre-determining the sandbox ID for async creation.// If empty, a new ID is generated automatically.SandboxID string `json:"-"`diff --git a/sdks/python/examples/test_declarative_images.py b/sdks/python/examples/test_declarative_images.pynew file mode 100644index 00000000..7445e17a--- /dev/null+++ b/sdks/python/examples/test_declarative_images.py@@ -0,0 +1,337 @@+#!/usr/bin/env python3+"""+Declarative Image Builder & Snapshots Test (Python SDK)++Tests both patterns for defining sandbox environments:++ Pattern 1 — On-demand images (cached by content hash):+ image = Image.base().apt_install(["curl"])+ sandbox = await Sandbox.create(image=image)++ Pattern 2 — Pre-built named snapshots:+ await snapshots.create(name="my-env", image=image)+ sandbox = await Sandbox.create(snapshot="my-env")++Usage:+ python examples/test_declarative_images.py+"""++import asyncio+import sys+import time++from opencomputer import Sandbox, Image, Snapshots++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"\033[32m\u2713 {msg}\033[0m")+++def red(msg: str) -> None:+ print(f"\033[31m\u2717 {msg}\033[0m")+++def bold(msg: str) -> None:+ print(f"\033[1m{msg}\033[0m")+++def dim(msg: str) -> None:+ print(f"\033[2m {msg}\033[0m")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════════╗")+ bold("║ Declarative Image Builder & Snapshots Test (Python) ║")+ bold("╚══════════════════════════════════════════════════════════╝\n")++ sandboxes: list[Sandbox] = []+ snapshots = Snapshots()++ try:+ # ── Test: Image builder basics ──────────────────────────────+ bold("━━━ Test: Image builder basics ━━━\n")++ base = Image.base()+ with_curl = base.apt_install(["curl"])+ with_python = with_curl.pip_install(["requests"])++ check("Image.base() uses default base", base.to_dict()["base"] == "base")+ check("Image is immutable — apt_install returns new instance", len(base.to_dict()["steps"]) == 0)+ check("Chained image has 1 step", len(with_curl.to_dict()["steps"]) == 1)+ check("Further chained image has 2 steps", len(with_python.to_dict()["steps"]) == 2)++ check("Different images have different cache keys", base.cache_key() != with_curl.cache_key())+ check("Same image produces same cache key", base.cache_key() == Image.base().cache_key())++ # File operations+ with_file = base.add_file("/workspace/config.json", '{"key": "value"}')+ check("add_file creates a step", len(with_file.to_dict()["steps"]) == 1)+ check("add_file step type is correct", with_file.to_dict()["steps"][0]["type"] == "add_file")+ print()++ # ── Pattern 1: On-demand image creation ────────────────────+ bold("━━━ Pattern 1: On-demand image (first build — cold) ━━━\n")++ image = (+ Image.base()+ .apt_install(["curl", "jq"])+ .run_commands("mkdir -p /workspace/project")+ .env({"MY_VAR": "hello-from-image", "PROJECT_ROOT": "/workspace/project"})+ .workdir("/workspace/project")+ )++ dim(f"Cache key: {image.cache_key()}")+ dim("Creating sandbox from image (this will build on first run)...")++ t1_start = time.time()+ sandbox1 = await Sandbox.create(image=image, timeout=300)+ t1_elapsed = int((time.time() - t1_start) * 1000)+ sandboxes.append(sandbox1)++ green(f"Sandbox created: {sandbox1.sandbox_id} ({t1_elapsed}ms)")+ check("Sandbox created successfully", sandbox1.status in ("running", "creating"))+ print()++ # ── Verify installed packages ──────────────────────────────+ bold("━━━ Verify: Packages installed ━━━\n")++ curl_check = await sandbox1.commands.run("which curl")+ check("curl is installed", curl_check.exit_code == 0, f"exit={curl_check.exit_code}")++ jq_check = await sandbox1.commands.run("which jq")+ check("jq is installed", jq_check.exit_code == 0, f"exit={jq_check.exit_code}")+ print()++ # ── Verify env vars ────────────────────────────────────────+ bold("━━━ Verify: Environment variables ━━━\n")++ env_check = await sandbox1.commands.run("bash -lc 'echo $MY_VAR'")+ check("MY_VAR is set", env_check.stdout.strip() == "hello-from-image", f'got: "{env_check.stdout.strip()}"')++ root_check = await sandbox1.commands.run("bash -lc 'echo $PROJECT_ROOT'")+ check("PROJECT_ROOT is set", root_check.stdout.strip() == "/workspace/project", f'got: "{root_check.stdout.strip()}"')+ print()++ # ── Cache hit: second sandbox from same image ──────────────+ bold("━━━ Pattern 1: Cache hit (second sandbox, same image) ━━━\n")++ dim("Creating second sandbox from same image (should be cached)...")+ t2_start = time.time()+ sandbox2 = await Sandbox.create(image=image, timeout=300)+ t2_elapsed = int((time.time() - t2_start) * 1000)+ sandboxes.append(sandbox2)++ green(f"Second sandbox created: {sandbox2.sandbox_id} ({t2_elapsed}ms)")++ if t1_elapsed > 5000:+ check(+ f"Cache hit is faster ({t2_elapsed}ms vs {t1_elapsed}ms cold build)",+ t2_elapsed < t1_elapsed,+ f"cold={t1_elapsed}ms, cached={t2_elapsed}ms",+ )+ else:+ dim(f"Cold build was fast ({t1_elapsed}ms) — skipping speedup check")++ curl_check2 = await sandbox2.commands.run("which curl")+ check("Cached sandbox also has curl", curl_check2.exit_code == 0)+ print()++ # Kill sandboxes before creating more+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass+ sandboxes.clear()++ # ── Pattern 2: Pre-built named snapshot ────────────────────+ bold("━━━ Pattern 2: Create named snapshot ━━━\n")++ snapshot_image = (+ Image.base()+ .run_commands(+ "echo 'snapshot-marker' > /workspace/snapshot-test.txt",+ "mkdir -p /workspace/data",+ )+ .env({"SNAPSHOT_ENV": "from-snapshot"})+ )++ dim("Creating snapshot 'test-env-py'...")+ snapshot_info = await snapshots.create(name="test-env-py", image=snapshot_image)+ green(f"Snapshot created: {snapshot_info['name']} (status={snapshot_info['status']})")+ check("Snapshot status is ready", snapshot_info["status"] == "ready")+ print()++ # ── List snapshots ─────────────────────────────────────────+ bold("━━━ Verify: List snapshots ━━━\n")++ snapshot_list = await snapshots.list()+ found = next((s for s in snapshot_list if s["name"] == "test-env-py"), None)+ check("Snapshot appears in list", found is not None)+ print()++ # ── Get snapshot by name ───────────────────────────────────+ bold("━━━ Verify: Get snapshot by name ━━━\n")++ fetched = await snapshots.get("test-env-py")+ check("Fetched snapshot matches", fetched["name"] == "test-env-py")+ check("Fetched snapshot is ready", fetched["status"] == "ready")+ print()++ # ── Create sandbox from named snapshot ─────────────────────+ bold("━━━ Pattern 2: Create sandbox from named snapshot ━━━\n")++ dim("Creating sandbox from snapshot 'test-env-py'...")+ sandbox3 = await Sandbox.create(snapshot="test-env-py", timeout=300)+ sandboxes.append(sandbox3)++ check("Sandbox created successfully", sandbox3.status in ("running", "creating"))++ marker_check = await sandbox3.commands.run("cat /workspace/snapshot-test.txt")+ check("Snapshot marker file exists", marker_check.stdout.strip() == "snapshot-marker", f'got: "{marker_check.stdout.strip()}"')++ snapshot_env_check = await sandbox3.commands.run("bash -lc 'echo $SNAPSHOT_ENV'")+ check("Snapshot env var is set", snapshot_env_check.stdout.strip() == "from-snapshot", f'got: "{snapshot_env_check.stdout.strip()}"')+ print()++ # ── Delete snapshot ────────────────────────────────────────+ bold("━━━ Cleanup: Delete snapshot ━━━\n")++ await snapshots.delete("test-env-py")+ green("Snapshot 'test-env-py' deleted")++ list_after = await snapshots.list()+ deleted_found = next((s for s in list_after if s["name"] == "test-env-py"), None)+ check("Snapshot no longer in list", deleted_found is None)+ print()++ # Kill sandbox before next test+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass+ sandboxes.clear()++ # ── Test: addFile step ─────────────────────────────────────+ bold("━━━ Test: add_file — bake files into the image ━━━\n")++ file_image = (+ Image.base()+ .add_file("/workspace/config.json", '{"env": "production", "debug": false}')+ .add_file("/workspace/setup.sh", "#!/bin/bash\necho 'Hello from setup!'")+ .run_commands("chmod +x /workspace/setup.sh")+ )++ dim("Creating sandbox with embedded files...")+ sandbox4 = await Sandbox.create(image=file_image, timeout=300)+ sandboxes.append(sandbox4)++ config_check = await sandbox4.commands.run("cat /workspace/config.json")+ check("add_file wrote config.json", '"env": "production"' in config_check.stdout, f'got: "{config_check.stdout.strip()}"')++ setup_check = await sandbox4.commands.run("/workspace/setup.sh")+ check("add_file wrote executable script", setup_check.stdout.strip() == "Hello from setup!", f'got: "{setup_check.stdout.strip()}"')+ print()++ # Kill sandbox before next test+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass+ sandboxes.clear()++ # ── Test: Build log streaming ──────────────────────────────+ bold("━━━ Test: Build log streaming (on_build_log callback) ━━━\n")++ log_image = Image.base().run_commands("echo 'build step 1'", "echo 'build step 2'")++ build_logs: list[str] = []+ dim("Creating sandbox with build log streaming...")+ sandbox5 = await Sandbox.create(+ image=log_image,+ timeout=300,+ on_build_log=lambda log: (build_logs.append(log), dim(f" build: {log}")),+ )+ sandboxes.append(sandbox5)++ check("Build log callback was called", len(build_logs) > 0, f"got {len(build_logs)} logs")+ check("Sandbox created via SSE stream", sandbox5.status in ("running", "creating"))+ print()++ # Kill sandbox before next test+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass+ sandboxes.clear()++ # ── Test: Snapshot build log streaming ──────────────────────+ bold("━━━ Test: Snapshot build log streaming (on_build_logs) ━━━\n")++ snapshot_log_image = Image.base().run_commands("echo 'snapshot build'")++ snapshot_logs: list[str] = []+ dim("Creating snapshot with build log streaming...")+ streamed_snapshot = await snapshots.create(+ name="test-streamed-py",+ image=snapshot_log_image,+ on_build_logs=lambda log: (snapshot_logs.append(log), dim(f" snapshot build: {log}")),+ )++ check("Snapshot build log callback was called", len(snapshot_logs) > 0, f"got {len(snapshot_logs)} logs")+ check("Streamed snapshot has name", streamed_snapshot["name"] == "test-streamed-py")+ check("Streamed snapshot is ready", streamed_snapshot["status"] == "ready")++ await snapshots.delete("test-streamed-py")+ green("Cleaned up test-streamed-py snapshot")+ print()++ except Exception as err:+ red(f"Fatal error: {err}")+ import traceback+ traceback.print_exc()+ failed += 1+ finally:+ bold("━━━ Cleanup ━━━\n")+ for sb in sandboxes:+ try:+ await sb.kill()+ dim(f"Killed {sb.sandbox_id}")+ except Exception:+ pass+ try:+ await snapshots.delete("test-env-py")+ except Exception:+ pass+ try:+ await snapshots.delete("test-streamed-py")+ except Exception:+ pass++ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.pyindex bb91090c..f9d472f9 100644--- a/sdks/python/opencomputer/__init__.py+++ b/sdks/python/opencomputer/__init__.py@@ -3,7 +3,9 @@from opencomputer.sandbox import Sandboxfrom opencomputer.filesystem import Filesystemfrom opencomputer.commands import Commands, ProcessResult+from opencomputer.image import Imagefrom opencomputer.pty import Pty, PtySession+from opencomputer.snapshot import Snapshotsfrom opencomputer.template import Template__all__ = [@@ -11,9 +13,11 @@ __all__ = ["Filesystem","Commands","ProcessResult",+ "Image","Pty","PtySession",+ "Snapshots","Template",]-__version__ = "0.4.4"+__version__ = "0.5.0"diff --git a/sdks/python/opencomputer/image.py b/sdks/python/opencomputer/image.pynew file mode 100644index 00000000..92fb16bd--- /dev/null+++ b/sdks/python/opencomputer/image.py@@ -0,0 +1,168 @@+"""Declarative image builder for OpenSandbox."""++from __future__ import annotations++import base64+import hashlib+import json+import os+from dataclasses import dataclass, field+from typing import Any+++@dataclass(frozen=True)+class ImageStep:+ type: str+ args: dict[str, Any]++ def to_dict(self) -> dict[str, Any]:+ return {"type": self.type, "args": self.args}+++@dataclass(frozen=True)+class Image:+ """Declarative image builder.++ Defines a reproducible sandbox environment via a fluent API.+ Under the hood, the manifest is sent to the server which boots a base sandbox,+ executes each step, checkpoints the result, and caches it by content hash.++ Example::++ image = (+ Image.base()+ .apt_install(["curl", "git"])+ .pip_install(["requests", "pandas"])+ .add_file("/workspace/config.json", '{"key": "value"}')+ .env({"PROJECT_ROOT": "/workspace"})+ .workdir("/workspace")+ )++ # On-demand: cached by content hash+ sandbox = await Sandbox.create(image=image)++ # Pre-built snapshot+ await Snapshot.create(name="data-science", image=image)+ """++ _base: str = "base"+ _steps: tuple[ImageStep, ...] = field(default_factory=tuple)++ @classmethod+ def base(cls) -> Image:+ """Create a new image starting from the default OpenSandbox environment.++ The base includes Ubuntu 22.04 with Python, Node.js, build tools, and+ common utilities. Customize by chaining steps like .apt_install(),+ .pip_install(), .run_commands(), etc.+ """+ return cls()++ def apt_install(self, packages: list[str]) -> Image:+ """Install system packages via apt-get."""+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("apt_install", {"packages": packages})),+ )++ def pip_install(self, packages: list[str]) -> Image:+ """Install Python packages via pip."""+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("pip_install", {"packages": packages})),+ )++ def run_commands(self, *commands: str) -> Image:+ """Run one or more shell commands."""+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("run", {"commands": list(commands)})),+ )++ def env(self, vars: dict[str, str]) -> Image:+ """Set environment variables (written to /etc/environment)."""+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("env", {"vars": vars})),+ )++ def workdir(self, path: str) -> Image:+ """Set the default working directory."""+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("workdir", {"path": path})),+ )++ def add_file(self, remote_path: str, content: str) -> Image:+ """Add a file with inline content to the image.++ Args:+ remote_path: Absolute path inside the sandbox where the file will be written.+ content: String content of the file.+ """+ encoded = base64.b64encode(content.encode()).decode()+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("add_file", {+ "path": remote_path,+ "content": encoded,+ "encoding": "base64",+ })),+ )++ def add_local_file(self, local_path: str, remote_path: str) -> Image:+ """Add a local file into the image.++ Reads the file from disk and embeds its content in the manifest.++ Args:+ local_path: Path to the file on the local machine.+ remote_path: Absolute path inside the sandbox where the file will be written.+ """+ with open(local_path, "rb") as f:+ encoded = base64.b64encode(f.read()).decode()+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("add_file", {+ "path": remote_path,+ "content": encoded,+ "encoding": "base64",+ })),+ )++ def add_local_dir(self, local_path: str, remote_path: str) -> Image:+ """Add a local directory into the image.++ Recursively reads all files and embeds them in the manifest.++ Args:+ local_path: Path to the directory on the local machine.+ remote_path: Absolute path inside the sandbox where the directory will be created.+ """+ files: list[dict[str, str]] = []+ for root, _dirs, filenames in os.walk(local_path):+ for fname in filenames:+ full = os.path.join(root, fname)+ rel = os.path.relpath(full, local_path)+ with open(full, "rb") as f:+ encoded = base64.b64encode(f.read()).decode()+ files.append({"relativePath": rel, "content": encoded})+ return Image(+ _base=self._base,+ _steps=(*self._steps, ImageStep("add_dir", {+ "path": remote_path,+ "files": files,+ })),+ )++ def to_dict(self) -> dict[str, Any]:+ """Returns the manifest as a plain dict (for JSON serialization)."""+ return {+ "base": self._base,+ "steps": [s.to_dict() for s in self._steps],+ }++ def cache_key(self) -> str:+ """Compute a deterministic content hash for caching."""+ canonical = json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(canonical.encode()).hexdigest()diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex 31368b7c..3ba71f14 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -4,13 +4,15 @@ from __future__ import annotationsimport osfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Callableimport httpxfrom opencomputer.commands import Commandsfrom opencomputer.filesystem import Filesystem+from opencomputer.image import Imagefrom opencomputer.pty import Pty+from opencomputer.sse import parse_sse_stream@dataclass@@ -36,8 +38,23 @@ class Sandbox:api_url: str | None = None,envs: dict[str, str] | None = None,metadata: dict[str, str] | None = None,+ image: Image | None = None,+ snapshot: str | None = None,+ on_build_log: Callable[[str], None] | None = None,) -> Sandbox:- """Create a new sandbox instance."""+ """Create a new sandbox instance.++ Args:+ template: Base template name (default "base").+ timeout: Sandbox timeout in seconds (default 300).+ api_key: API key (or OPENCOMPUTER_API_KEY env var).+ api_url: API URL (or OPENCOMPUTER_API_URL env var).+ envs: Environment variables to inject.+ metadata: Arbitrary metadata tags.+ image: Declarative Image definition. The server builds and caches it as a checkpoint.+ snapshot: Name of a pre-built snapshot to create the sandbox from.+ on_build_log: Callback for build log streaming when using image/snapshot.+ """url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")url = url.rstrip("/")key = api_key or os.environ.get("OPENCOMPUTER_API_KEY", "")@@ -45,11 +62,17 @@ class Sandbox:# Control plane client always uses /api prefixapi_base = url if url.endswith("/api") else f"{url}/api"- headers = {}+ headers: dict[str, str] = {}if key:headers["X-API-Key"] = key- client = httpx.AsyncClient(base_url=api_base, headers=headers, timeout=30.0)+ use_sse = on_build_log is not None and (image is not None or snapshot is not None)+ if use_sse:+ headers["Accept"] = "text/event-stream"++ # Image builds may take longer+ client_timeout = 300.0 if image else 30.0+ client = httpx.AsyncClient(base_url=api_base, headers=headers, timeout=client_timeout)body: dict[str, Any] = {"templateID": template,@@ -59,10 +82,17 @@ class Sandbox:body["envs"] = envsif metadata:body["metadata"] = metadata-- resp = await client.post("/sandboxes", json=body)- resp.raise_for_status()- data = resp.json()+ if image is not None:+ body["image"] = image.to_dict()+ if snapshot is not None:+ body["snapshot"] = snapshot++ if use_sse:+ data = await cls._create_with_sse(client, body, on_build_log)+ else:+ resp = await client.post("/sandboxes", json=body)+ resp.raise_for_status()+ data = resp.json()connect_url = data.get("connectURL", "")token = data.get("token", "")@@ -88,6 +118,18 @@ class Sandbox:_data_client=data_client,)+ @classmethod+ async def _create_with_sse(+ cls,+ client: httpx.AsyncClient,+ body: dict[str, Any],+ on_build_log: Callable[[str], None] | None,+ ) -> dict[str, Any]:+ """Create sandbox with SSE build log streaming."""+ async with client.stream("POST", "/sandboxes", json=body) as resp:+ resp.raise_for_status()+ return await parse_sse_stream(resp, on_build_log or (lambda _: None))+@classmethodasync def connect(cls,diff --git a/sdks/python/opencomputer/snapshot.py b/sdks/python/opencomputer/snapshot.pynew file mode 100644index 00000000..0b22510c--- /dev/null+++ b/sdks/python/opencomputer/snapshot.py@@ -0,0 +1,105 @@+"""Snapshot management for OpenSandbox - pre-built named image checkpoints."""++from __future__ import annotations++import os+from typing import Any, Callable++import httpx++from opencomputer.image import Image+from opencomputer.sse import parse_sse_stream+++class Snapshots:+ """Manage pre-built snapshots (named, persistent image checkpoints).++ Example::++ snapshots = Snapshots()++ image = (+ Image.base()+ .apt_install(["python3", "python3-pip"])+ .pip_install(["pandas", "numpy"])+ )++ await snapshots.create(name="data-science", image=image)+ info = await snapshots.get("data-science")+ all_snapshots = await snapshots.list()+ await snapshots.delete("data-science")+ """++ def __init__(+ self,+ api_key: str | None = None,+ api_url: str | None = None,+ ) -> None:+ url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")+ url = url.rstrip("/")+ key = api_key or os.environ.get("OPENCOMPUTER_API_KEY", "")++ api_base = url if url.endswith("/api") else f"{url}/api"++ self._headers: dict[str, str] = {}+ if key:+ self._headers["X-API-Key"] = key++ self._api_base = api_base+ self._client = httpx.AsyncClient(base_url=api_base, headers=self._headers, timeout=300.0)++ async def create(+ self,+ name: str,+ image: Image,+ on_build_logs: Callable[[str], None] | None = None,+ ) -> dict[str, Any]:+ """Create a pre-built snapshot from a declarative image.++ Args:+ name: Unique name for this snapshot.+ image: Declarative Image definition.+ on_build_logs: Optional callback for build log streaming.++ Returns:+ Snapshot info dict with id, name, status, etc.+ """+ body = {"name": name, "image": image.to_dict()}++ if on_build_logs is not None:+ headers = {**self._headers, "Accept": "text/event-stream"}+ client = httpx.AsyncClient(+ base_url=self._api_base, headers=headers, timeout=300.0,+ )+ try:+ async with client.stream("POST", "/snapshots", json=body) as resp:+ resp.raise_for_status()+ return await parse_sse_stream(resp, on_build_logs)+ finally:+ await client.aclose()++ resp = await self._client.post("/snapshots", json=body)+ resp.raise_for_status()+ return resp.json()++ async def list(self) -> list[dict[str, Any]]:+ """List all named snapshots for the current org."""+ resp = await self._client.get("/snapshots")+ resp.raise_for_status()+ return resp.json()++ async def get(self, name: str) -> dict[str, Any]:+ """Get a snapshot by name."""+ resp = await self._client.get(f"/snapshots/{name}")+ resp.raise_for_status()+ return resp.json()++ async def delete(self, name: str) -> None:+ """Delete a named snapshot."""+ resp = await self._client.delete(f"/snapshots/{name}")+ if resp.status_code != 404:+ resp.raise_for_status()++ async def close(self) -> None:+ """Close the HTTP client."""+ await self._client.aclose()diff --git a/sdks/python/opencomputer/sse.py b/sdks/python/opencomputer/sse.pynew file mode 100644index 00000000..cbc97d43--- /dev/null+++ b/sdks/python/opencomputer/sse.py@@ -0,0 +1,73 @@+"""Shared SSE stream parser for build log streaming."""++from __future__ import annotations++import json+from typing import Any, Callable++import httpx+++async def parse_sse_stream(+ resp: httpx.Response,+ on_log: Callable[[str], None],+) -> dict[str, Any]:+ """Parse an SSE stream from the server.++ The server emits three event types:+ - build_log: streamed during image build, contains { step, type, message }+ - error: build failed, contains { error: string }+ - result: final result JSON++ Args:+ resp: httpx streaming response with content-type text/event-stream+ on_log: Callback for build log messages++ Returns:+ The parsed result dict from the "result" event++ Raises:+ RuntimeError: If the build fails or no result is received+ """+ result: dict[str, Any] | None = None+ buffer = ""++ async for chunk in resp.aiter_text():+ buffer += chunk+ events = buffer.split("\n\n")+ buffer = events[-1]++ for event in events[:-1]:+ if not event.strip():+ continue++ event_type = ""+ data = ""+ for line in event.split("\n"):+ if line.startswith("event: "):+ event_type = line[7:]+ elif line.startswith("data: "):+ data = line[6:]++ if not data:+ continue++ if event_type == "build_log":+ try:+ parsed = json.loads(data)+ on_log(parsed.get("message", data))+ except (json.JSONDecodeError, TypeError):+ on_log(data)+ elif event_type == "error":+ msg = data+ try:+ msg = json.loads(data).get("error", data)+ except (json.JSONDecodeError, TypeError):+ pass+ raise RuntimeError(f"Build failed: {msg}")+ elif event_type == "result":+ result = json.loads(data)++ if not result:+ raise RuntimeError("No result received from build stream")+ return resultdiff --git a/sdks/typescript/examples/test-declarative-images.ts b/sdks/typescript/examples/test-declarative-images.tsnew file mode 100644index 00000000..7f87867e--- /dev/null+++ b/sdks/typescript/examples/test-declarative-images.ts@@ -0,0 +1,375 @@+/**+ * Declarative Image Builder & Snapshots Test+ *+ * Demonstrates and tests both patterns for defining sandbox environments:+ *+ * Pattern 1 — On-demand images (cached by content hash):+ * const image = Image.base('ubuntu').aptInstall(['curl']).pipInstall(['requests'])+ * const sandbox = await Sandbox.create({ image })+ *+ * Pattern 2 — Pre-built named snapshots:+ * await snapshots.create({ name: 'my-env', image })+ * const sandbox = await Sandbox.create({ snapshot: 'my-env' })+ *+ * Tests:+ * 1. Build an image with apt + pip + env + workdir+ * 2. Create sandbox from image (first build — cold)+ * 3. Verify packages are installed+ * 4. Verify env vars are set+ * 5. Verify workdir was created+ * 6. Create a second sandbox from the same image (cache hit — fast)+ * 7. Verify cache hit was significantly faster+ * 8. Create a named snapshot from an image+ * 9. List snapshots+ * 10. Create sandbox from named snapshot+ * 11. Verify snapshot sandbox has correct state+ * 12. Delete snapshot+ * 13. Image immutability — chaining produces new instances+ * 14. runCommands step+ *+ * Usage:+ * npx tsx examples/test-declarative-images.ts+ */++import { Sandbox, Image, Snapshots } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }++let passed = 0;+let failed = 0;++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) {+ green(desc);+ passed++;+ } else {+ red(`${desc}${detail ? ` (${detail})` : ""}`);+ failed++;+ }+}++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Declarative Image Builder & Snapshots Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ const sandboxes: Sandbox[] = [];+ const snapshots = new Snapshots();++ try {+ // ── Test: Image class immutability ─────────────────────────────+ bold("━━━ Test: Image builder basics ━━━\n");++ const base = Image.base();+ const withCurl = base.aptInstall(["curl"]);+ const withPython = withCurl.pipInstall(["requests"]);++ check("Image.base() uses default base", base.toJSON().base === "base");+ check("Image is immutable — aptInstall returns new instance", base.toJSON().steps.length === 0);+ check("Chained image has 1 step", withCurl.toJSON().steps.length === 1);+ check("Further chained image has 2 steps", withPython.toJSON().steps.length === 2);++ // Cache keys should differ+ check("Different images have different cache keys", base.cacheKey() !== withCurl.cacheKey());+ check("Same image produces same cache key", base.cacheKey() === Image.base().cacheKey());++ // File operations+ const withFile = base.addFile("/workspace/config.json", '{"key": "value"}');+ check("addFile creates a step", withFile.toJSON().steps.length === 1);+ check("addFile step type is correct", withFile.toJSON().steps[0].type === "add_file");+ console.log();++ // ── Pattern 1: On-demand image creation ───────────────────────+ bold("━━━ Pattern 1: On-demand image (first build — cold) ━━━\n");++ const image = Image.base()+ .aptInstall(["curl", "jq"])+ .runCommands("mkdir -p /workspace/project")+ .env({ MY_VAR: "hello-from-image", PROJECT_ROOT: "/workspace/project" })+ .workdir("/workspace/project");++ dim(`Image manifest: ${JSON.stringify(image.toJSON(), null, 2)}`);+ dim(`Cache key: ${image.cacheKey()}`);+ dim("Creating sandbox from image (this will build on first run)...");++ const t1Start = Date.now();+ const sandbox1 = await Sandbox.create({ image, timeout: 300 });+ const t1Elapsed = Date.now() - t1Start;+ sandboxes.push(sandbox1);++ green(`Sandbox created: ${sandbox1.sandboxId} (${t1Elapsed}ms)`);+ check("Sandbox created successfully", sandbox1.status === "running" || sandbox1.status === "creating");+ console.log();++ // ── Verify installed packages ─────────────────────────────────+ bold("━━━ Verify: Packages installed ━━━\n");++ const curlCheck = await sandbox1.commands.run("which curl");+ check("curl is installed", curlCheck.exitCode === 0, `exit=${curlCheck.exitCode}`);++ const jqCheck = await sandbox1.commands.run("which jq");+ check("jq is installed", jqCheck.exitCode === 0, `exit=${jqCheck.exitCode}`);+ console.log();++ // ── Verify env vars ───────────────────────────────────────────+ bold("━━━ Verify: Environment variables ━━━\n");++ const envCheck = await sandbox1.commands.run("bash -lc 'echo $MY_VAR'");+ check("MY_VAR is set", envCheck.stdout.trim() === "hello-from-image", `got: "${envCheck.stdout.trim()}"`);++ const rootCheck = await sandbox1.commands.run("bash -lc 'echo $PROJECT_ROOT'");+ check("PROJECT_ROOT is set", rootCheck.stdout.trim() === "/workspace/project", `got: "${rootCheck.stdout.trim()}"`);+ console.log();++ // ── Verify workdir ────────────────────────────────────────────+ bold("━━━ Verify: Working directory ━━━\n");++ const dirCheck = await sandbox1.commands.run("test -d /workspace/project && echo exists");+ check("/workspace/project exists", dirCheck.stdout.trim() === "exists");+ console.log();++ // ── Cache hit: second sandbox from same image ─────────────────+ bold("━━━ Pattern 1: Cache hit (second sandbox, same image) ━━━\n");++ dim("Creating second sandbox from same image (should be cached)...");+ const t2Start = Date.now();+ const sandbox2 = await Sandbox.create({ image, timeout: 300 });+ const t2Elapsed = Date.now() - t2Start;+ sandboxes.push(sandbox2);++ green(`Second sandbox created: ${sandbox2.sandboxId} (${t2Elapsed}ms)`);++ // Cache hit should be faster (no build step)+ if (t1Elapsed > 5000) {+ // Only check speedup if cold build took meaningful time+ check(+ `Cache hit is faster (${t2Elapsed}ms vs ${t1Elapsed}ms cold build)`,+ t2Elapsed < t1Elapsed,+ `cold=${t1Elapsed}ms, cached=${t2Elapsed}ms`+ );+ } else {+ dim(`Cold build was fast (${t1Elapsed}ms) — skipping speedup check`);+ }++ // Verify cached sandbox also has the packages+ const curlCheck2 = await sandbox2.commands.run("which curl");+ check("Cached sandbox also has curl", curlCheck2.exitCode === 0);+ console.log();++ // Kill sandboxes before creating more (avoid hitting org concurrency limits)+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch { /* best effort */ }+ }+ sandboxes.length = 0;++ // ── Pattern 2: Pre-built named snapshot ───────────────────────+ bold("━━━ Pattern 2: Create named snapshot ━━━\n");++ const snapshotImage = Image.base()+ .runCommands(+ "echo 'snapshot-marker' > /workspace/snapshot-test.txt",+ "mkdir -p /workspace/data"+ )+ .env({ SNAPSHOT_ENV: "from-snapshot" });++ dim("Creating snapshot 'test-env'...");+ const snapshotInfo = await snapshots.create({+ name: "test-env",+ image: snapshotImage,+ });+ green(`Snapshot created: ${snapshotInfo.name} (status=${snapshotInfo.status})`);+ check("Snapshot status is ready", snapshotInfo.status === "ready");+ console.log();++ // ── List snapshots ────────────────────────────────────────────+ bold("━━━ Verify: List snapshots ━━━\n");++ const snapshotList = await snapshots.list();+ const found = snapshotList.find((s) => s.name === "test-env");+ check("Snapshot appears in list", found !== undefined);+ check("Snapshot has correct name", found?.name === "test-env");+ console.log();++ // ── Get snapshot by name ──────────────────────────────────────+ bold("━━━ Verify: Get snapshot by name ━━━\n");++ const fetched = await snapshots.get("test-env");+ check("Fetched snapshot matches", fetched.name === "test-env");+ check("Fetched snapshot is ready", fetched.status === "ready");+ console.log();++ // ── Create sandbox from named snapshot ────────────────────────+ bold("━━━ Pattern 2: Create sandbox from named snapshot ━━━\n");++ dim("Creating sandbox from snapshot 'test-env'...");+ const t3Start = Date.now();+ const sandbox3 = await Sandbox.create({ snapshot: "test-env", timeout: 300 });+ const t3Elapsed = Date.now() - t3Start;+ sandboxes.push(sandbox3);++ green(`Sandbox from snapshot: ${sandbox3.sandboxId} (${t3Elapsed}ms)`);+ check("Sandbox created successfully", sandbox3.status === "running" || sandbox3.status === "creating");++ // Verify snapshot state+ const markerCheck = await sandbox3.commands.run("cat /workspace/snapshot-test.txt");+ check("Snapshot marker file exists", markerCheck.stdout.trim() === "snapshot-marker", `got: "${markerCheck.stdout.trim()}"`);++ const snapshotEnvCheck = await sandbox3.commands.run("bash -lc 'echo $SNAPSHOT_ENV'");+ check("Snapshot env var is set", snapshotEnvCheck.stdout.trim() === "from-snapshot", `got: "${snapshotEnvCheck.stdout.trim()}"`);++ const dataDirCheck = await sandbox3.commands.run("test -d /workspace/data && echo exists");+ check("/workspace/data exists", dataDirCheck.stdout.trim() === "exists");+ console.log();++ // ── Delete snapshot ───────────────────────────────────────────+ bold("━━━ Cleanup: Delete snapshot ━━━\n");++ await snapshots.delete("test-env");+ green("Snapshot 'test-env' deleted");++ const listAfterDelete = await snapshots.list();+ const deletedFound = listAfterDelete.find((s) => s.name === "test-env");+ check("Snapshot no longer in list", deletedFound === undefined);+ console.log();++ // Kill snapshot sandbox before creating more+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch { /* best effort */ }+ }+ sandboxes.length = 0;++ // ── Test: runCommands with multiple commands ──────────────────+ bold("━━━ Test: runCommands with multiple commands ━━━\n");++ const multiImage = Image.base()+ .runCommands(+ "echo hello > /workspace/a.txt",+ "echo world > /workspace/b.txt",+ "cat /workspace/a.txt /workspace/b.txt > /workspace/combined.txt"+ );++ dim("Creating sandbox with multi-command image...");+ const sandbox4 = await Sandbox.create({ image: multiImage, timeout: 300 });+ sandboxes.push(sandbox4);++ const combined = await sandbox4.commands.run("cat /workspace/combined.txt");+ check("Multiple runCommands executed", combined.stdout.includes("hello") && combined.stdout.includes("world"), `got: "${combined.stdout.trim()}"`);+ console.log();++ // Kill sandboxes before next test+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch { /* best effort */ }+ }+ sandboxes.length = 0;++ // ── Test: addFile step ──────────────────────────────────────────+ bold("━━━ Test: addFile — bake files into the image ━━━\n");++ const fileImage = Image.base()+ .addFile("/workspace/config.json", '{"env": "production", "debug": false}')+ .addFile("/workspace/setup.sh", "#!/bin/bash\necho 'Hello from setup!'")+ .runCommands("chmod +x /workspace/setup.sh");++ dim("Creating sandbox with embedded files...");+ const sandbox5 = await Sandbox.create({ image: fileImage, timeout: 300 });+ sandboxes.push(sandbox5);++ const configCheck = await sandbox5.commands.run("cat /workspace/config.json");+ check("addFile wrote config.json", configCheck.stdout.includes('"env": "production"'), `got: "${configCheck.stdout.trim()}"`);++ const setupCheck = await sandbox5.commands.run("/workspace/setup.sh");+ check("addFile wrote executable script", setupCheck.stdout.trim() === "Hello from setup!", `got: "${setupCheck.stdout.trim()}"`);+ console.log();++ // Kill sandboxes before next test+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch { /* best effort */ }+ }+ sandboxes.length = 0;++ // ── Test: Build log streaming ───────────────────────────────────+ bold("━━━ Test: Build log streaming (onBuildLog callback) ━━━\n");++ const logImage = Image.base()+ .runCommands("echo 'build step 1'", "echo 'build step 2'");++ const buildLogs: string[] = [];+ dim("Creating sandbox with build log streaming...");+ const sandbox6 = await Sandbox.create({+ image: logImage,+ timeout: 300,+ onBuildLog: (log) => {+ buildLogs.push(log);+ dim(` build: ${log}`);+ },+ });+ sandboxes.push(sandbox6);++ check("Build log callback was called", buildLogs.length > 0, `got ${buildLogs.length} logs`);+ check("Sandbox created via SSE stream", sandbox6.status === "running" || sandbox6.status === "creating");+ console.log();++ // Kill sandboxes before next test+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch { /* best effort */ }+ }+ sandboxes.length = 0;++ // ── Test: Snapshot build log streaming ──────────────────────────+ bold("━━━ Test: Snapshot build log streaming (onBuildLogs) ━━━\n");++ const snapshotLogImage = Image.base()+ .runCommands("echo 'snapshot build'");++ const snapshotLogs: string[] = [];+ dim("Creating snapshot with build log streaming...");+ const streamedSnapshot = await snapshots.create({+ name: "test-streamed",+ image: snapshotLogImage,+ onBuildLogs: (log) => {+ snapshotLogs.push(log);+ dim(` snapshot build: ${log}`);+ },+ });++ check("Snapshot build log callback was called", snapshotLogs.length > 0, `got ${snapshotLogs.length} logs`);+ check("Streamed snapshot has name", streamedSnapshot.name === "test-streamed");+ check("Streamed snapshot is ready", streamedSnapshot.status === "ready");++ // Cleanup streamed snapshot+ await snapshots.delete("test-streamed");+ green("Cleaned up test-streamed snapshot");+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ // Cleanup: kill all sandboxes+ bold("━━━ Cleanup ━━━\n");+ for (const sb of sandboxes) {+ try {+ await sb.kill();+ dim(`Killed ${sb.sandboxId}`);+ } catch { /* best effort */ }+ }+ // Clean up any leftover test snapshots+ try { await snapshots.delete("test-env"); } catch { /* may already be deleted */ }+ try { await snapshots.delete("test-streamed"); } catch { /* may already be deleted */ }+ }++ // --- Summary ---+ bold("========================================");+ bold(` Results: ${passed} passed, ${failed} failed`);+ bold("========================================\n");+ if (failed > 0) process.exit(1);+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/sdks/typescript/src/image.ts b/sdks/typescript/src/image.tsnew file mode 100644index 00000000..e580bea9--- /dev/null+++ b/sdks/typescript/src/image.ts@@ -0,0 +1,181 @@+import { createHash } from "crypto";+import { readFileSync, readdirSync, statSync } from "fs";+import { join, relative } from "path";++export interface ImageStep {+ type: "apt_install" | "pip_install" | "run" | "env" | "workdir" | "add_file" | "add_dir";+ args: Record<string, unknown>;+}++export interface ImageManifest {+ base: string;+ steps: ImageStep[];+}++/**+ * Declarative image builder for OpenSandbox.+ *+ * Defines a reproducible sandbox environment via a fluent API.+ * Under the hood, the manifest is sent to the server which boots a base sandbox,+ * executes each step, checkpoints the result, and caches it by content hash.+ *+ * @example+ * ```typescript+ * const image = Image.base()+ * .aptInstall(['curl', 'git'])+ * .pipInstall(['requests', 'pandas'])+ * .addFile('/workspace/config.json', '{"key": "value"}')+ * .env({ PROJECT_ROOT: '/workspace' })+ * .workdir('/workspace')+ *+ * // On-demand: cached by content hash+ * const sandbox = await Sandbox.create({ image })+ *+ * // Pre-built snapshot+ * const snapshots = new Snapshots()+ * await snapshots.create({ name: 'data-science', image })+ * ```+ */+export class Image {+ private readonly manifest: ImageManifest;++ private constructor(steps: ImageStep[] = []) {+ this.manifest = { base: "base", steps };+ }++ /**+ * Create a new image starting from the default OpenSandbox environment+ * (Ubuntu 22.04 with Python, Node.js, build tools, and common utilities).+ * Customize by chaining steps like `.aptInstall()`, `.pipInstall()`, `.runCommands()`, etc.+ */+ static base(): Image {+ return new Image();+ }++ /**+ * Install system packages via apt-get.+ */+ aptInstall(packages: string[]): Image {+ return new Image([+ ...this.manifest.steps,+ { type: "apt_install", args: { packages } },+ ]);+ }++ /**+ * Install Python packages via pip.+ */+ pipInstall(packages: string[]): Image {+ return new Image([+ ...this.manifest.steps,+ { type: "pip_install", args: { packages } },+ ]);+ }++ /**+ * Run one or more shell commands.+ */+ runCommands(...commands: string[]): Image {+ return new Image([+ ...this.manifest.steps,+ { type: "run", args: { commands } },+ ]);+ }++ /**+ * Set environment variables (written to /etc/environment).+ */+ env(vars: Record<string, string>): Image {+ return new Image([+ ...this.manifest.steps,+ { type: "env", args: { vars } },+ ]);+ }++ /**+ * Set the default working directory.+ */+ workdir(path: string): Image {+ return new Image([+ ...this.manifest.steps,+ { type: "workdir", args: { path } },+ ]);+ }++ /**+ * Add a file with inline content to the image.+ * @param remotePath - Absolute path inside the sandbox where the file will be written.+ * @param content - String content of the file.+ */+ addFile(remotePath: string, content: string): Image {+ const encoded = Buffer.from(content).toString("base64");+ return new Image([+ ...this.manifest.steps,+ { type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } },+ ]);+ }++ /**+ * Add a local file into the image.+ * Reads the file from disk and embeds its content in the manifest.+ * @param localPath - Path to the file on the local machine.+ * @param remotePath - Absolute path inside the sandbox where the file will be written.+ */+ addLocalFile(localPath: string, remotePath: string): Image {+ const content = readFileSync(localPath);+ const encoded = content.toString("base64");+ return new Image([+ ...this.manifest.steps,+ { type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } },+ ]);+ }++ /**+ * Add a local directory into the image.+ * Recursively reads all files and embeds them in the manifest.+ * @param localPath - Path to the directory on the local machine.+ * @param remotePath - Absolute path inside the sandbox where the directory will be created.+ */+ addLocalDir(localPath: string, remotePath: string): Image {+ const files: Array<{ relativePath: string; content: string }> = [];+ collectFiles(localPath, localPath, files);+ return new Image([+ ...this.manifest.steps,+ { type: "add_dir", args: { path: remotePath, files } },+ ]);+ }++ /**+ * Returns the manifest as a plain object (for JSON serialization).+ */+ toJSON(): ImageManifest {+ return this.manifest;+ }++ /**+ * Compute a deterministic content hash for caching.+ */+ cacheKey(): string {+ const canonical = JSON.stringify(this.manifest);+ return createHash("sha256").update(canonical).digest("hex");+ }+}++function collectFiles(+ basePath: string,+ currentPath: string,+ out: Array<{ relativePath: string; content: string }>+): void {+ for (const entry of readdirSync(currentPath)) {+ const full = join(currentPath, entry);+ const stat = statSync(full);+ if (stat.isDirectory()) {+ collectFiles(basePath, full, out);+ } else if (stat.isFile()) {+ out.push({+ relativePath: relative(basePath, full),+ content: readFileSync(full).toString("base64"),+ });+ }+ }+}diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex 9b161035..adf5c76b 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -3,3 +3,5 @@ export { Filesystem, type EntryInfo } from "./filesystem.js";export { Commands, type ProcessResult, type RunOpts } from "./commands.js";export { Pty, type PtySession, type PtyOpts } from "./pty.js";export { Templates, type TemplateInfo } from "./template.js";+export { Image, type ImageManifest, type ImageStep } from "./image.js";+export { Snapshots, type SnapshotInfo, type CreateSnapshotOpts } from "./snapshot.js";diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 9b81584c..d4e64b1f 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -1,12 +1,15 @@import { Filesystem } from "./filesystem.js";import { Commands } from "./commands.js";import { Pty } from "./pty.js";+import { Image } from "./image.js";+import { parseSSEStream } from "./sse.js";function resolveApiUrl(url: string): string {const base = url.replace(/\/+$/, "");return base.endsWith("/api") ? base : `${base}/api`;}+export interface SandboxOpts {template?: string;timeout?: number;@@ -16,6 +19,12 @@ export interface SandboxOpts {metadata?: Record<string, string>;cpuCount?: number;memoryMB?: number;+ /** Declarative image definition. The server builds and caches it as a checkpoint. */+ image?: Image;+ /** Name of a pre-built snapshot to create the sandbox from. */+ snapshot?: string;+ /** Callback for build log streaming when using `image`. Called with each build step message. */+ onBuildLog?: (log: string) => void;}interface SandboxData {@@ -112,13 +121,22 @@ export class Sandbox {if (opts.metadata) body.metadata = opts.metadata;if (opts.cpuCount != null) body.cpuCount = opts.cpuCount;if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;+ if (opts.image) body.image = opts.image.toJSON();+ if (opts.snapshot) body.snapshot = opts.snapshot;++ const useSSE = opts.onBuildLog && (opts.image || opts.snapshot);++ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ ...(apiKey ? { "X-API-Key": apiKey } : {}),+ };+ if (useSSE) {+ headers["Accept"] = "text/event-stream";+ }const resp = await fetch(`${apiUrl}/sandboxes`, {method: "POST",- headers: {- "Content-Type": "application/json",- ...(apiKey ? { "X-API-Key": apiKey } : {}),- },+ headers,body: JSON.stringify(body),});@@ -127,6 +145,11 @@ export class Sandbox {throw new Error(`Failed to create sandbox: ${resp.status} ${text}`);}+ if (useSSE && resp.headers.get("content-type")?.includes("text/event-stream")) {+ const data = await parseSSEStream<SandboxData>(resp, opts.onBuildLog!);+ return new Sandbox(data, apiUrl, apiKey);+ }+const data: SandboxData = await resp.json();return new Sandbox(data, apiUrl, apiKey);}diff --git a/sdks/typescript/src/snapshot.ts b/sdks/typescript/src/snapshot.tsnew file mode 100644index 00000000..56cef097--- /dev/null+++ b/sdks/typescript/src/snapshot.ts@@ -0,0 +1,126 @@+import { Image } from "./image.js";+import { parseSSEStream } from "./sse.js";++function resolveApiUrl(url: string): string {+ const base = url.replace(/\/+$/, "");+ return base.endsWith("/api") ? base : `${base}/api`;+}++export interface SnapshotInfo {+ id: string;+ orgId: string;+ name: string;+ contentHash: string;+ checkpointId: string;+ status: string;+ manifest: Record<string, unknown>;+ createdAt: string;+ lastUsedAt: string;+}++export interface CreateSnapshotOpts {+ name: string;+ image: Image;+ onBuildLogs?: (log: string) => void;+}++export interface SnapshotOpts {+ apiKey?: string;+ apiUrl?: string;+}++/**+ * Manage pre-built snapshots (named, persistent image checkpoints).+ */+export class Snapshots {+ private apiUrl: string;+ private apiKey: string;++ constructor(opts: SnapshotOpts = {}) {+ this.apiUrl = resolveApiUrl(+ opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev"+ );+ this.apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";+ }++ private get headers(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (this.apiKey) h["X-API-Key"] = this.apiKey;+ return h;+ }++ /**+ * Create a pre-built snapshot from a declarative image.+ * The server boots a sandbox, runs the image steps, checkpoints it, and stores it under the given name.+ */+ async create(opts: CreateSnapshotOpts): Promise<SnapshotInfo> {+ const headers: Record<string, string> = { ...this.headers };+ if (opts.onBuildLogs) {+ headers["Accept"] = "text/event-stream";+ }++ const resp = await fetch(`${this.apiUrl}/snapshots`, {+ method: "POST",+ headers,+ body: JSON.stringify({+ name: opts.name,+ image: opts.image.toJSON(),+ }),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to create snapshot: ${resp.status} ${text}`);+ }++ if (opts.onBuildLogs && resp.headers.get("content-type")?.includes("text/event-stream")) {+ return parseSSEStream<SnapshotInfo>(resp, opts.onBuildLogs);+ }++ return resp.json();+ }++ /**+ * List all named snapshots for the current org.+ */+ async list(): Promise<SnapshotInfo[]> {+ const resp = await fetch(`${this.apiUrl}/snapshots`, {+ headers: this.headers,+ });++ if (!resp.ok) {+ throw new Error(`Failed to list snapshots: ${resp.status}`);+ }++ return resp.json();+ }++ /**+ * Get a snapshot by name.+ */+ async get(name: string): Promise<SnapshotInfo> {+ const resp = await fetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {+ headers: this.headers,+ });++ if (!resp.ok) {+ throw new Error(`Failed to get snapshot: ${resp.status}`);+ }++ return resp.json();+ }++ /**+ * Delete a named snapshot.+ */+ async delete(name: string): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {+ method: "DELETE",+ headers: this.headers,+ });++ if (!resp.ok && resp.status !== 404) {+ throw new Error(`Failed to delete snapshot: ${resp.status}`);+ }+ }+}diff --git a/sdks/typescript/src/sse.ts b/sdks/typescript/src/sse.tsnew file mode 100644index 00000000..dc821005--- /dev/null+++ b/sdks/typescript/src/sse.ts@@ -0,0 +1,65 @@+/**+ * Parse an SSE stream from the server.+ *+ * The server emits three event types:+ * - `build_log`: streamed during image build, contains `{ step, type, message }`+ * - `error`: build failed, contains `{ error: string }`+ * - `result`: final result JSON (sandbox data, snapshot info, etc.)+ *+ * @param resp - Fetch Response with content-type text/event-stream+ * @param onLog - Callback for build log messages+ * @returns The parsed result from the "result" event+ */+export async function parseSSEStream<T>(resp: Response, onLog: (msg: string) => void): Promise<T> {+ const reader = resp.body?.getReader();+ if (!reader) throw new Error("No response body for SSE stream");++ const decoder = new TextDecoder();+ let buffer = "";+ let result: T | null = null;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n\n");+ buffer = parts.pop() ?? "";++ for (const part of parts) {+ if (!part.trim()) continue;++ let eventType = "";+ let data = "";+ for (const line of part.split("\n")) {+ if (line.startsWith("event: ")) eventType = line.slice(7);+ else if (line.startsWith("data: ")) data = line.slice(6);+ }++ if (!data) continue;++ switch (eventType) {+ case "build_log": {+ try {+ onLog(JSON.parse(data).message ?? data);+ } catch {+ onLog(data);+ }+ break;+ }+ case "error": {+ let msg = data;+ try { msg = JSON.parse(data).error ?? data; } catch {}+ throw new Error(`Build failed: ${msg}`);+ }+ case "result": {+ result = JSON.parse(data);+ break;+ }+ }+ }+ }++ if (!result) throw new Error("No result received from build stream");+ return result;+}