Skip to content

An open-source, faster Devin alternative

TypeScript

Merge main into secrets-change: resolve conflicts keeping both secrets and image/snapshot features

motatoes892619b17018
diff --cc internal/api/router.go
index d2078c99,c9ee7470..42ebb0ed
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@@ -155,52 -176,77 +176,89 @@@ func NewServer(mgr sandbox.Manager, pty
api.GET("/sandboxes/:id/preview", s.listPreviewURLs)
api.DELETE("/sandboxes/:id/preview/:port", s.deletePreviewURL)
- // Exec sessions (replaces old /commands)
- api.POST("/sandboxes/:id/exec", s.createExecSession)
- api.GET("/sandboxes/:id/exec", s.listExecSessions)
- api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
- api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
- api.POST("/sandboxes/:id/exec/run", s.execRun)
-
- // Agent sessions (Claude Agent SDK)
- api.POST("/sandboxes/:id/agent", s.createAgentSession)
- api.GET("/sandboxes/:id/agent", s.listAgentSessions)
- api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
- api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
- api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
-
- // Filesystem
- api.GET("/sandboxes/:id/files", s.readFile)
- api.PUT("/sandboxes/:id/files", s.writeFile)
- api.GET("/sandboxes/:id/files/list", s.listDir)
- api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
- api.DELETE("/sandboxes/:id/files", s.removeFile)
-
- // PTY
- api.POST("/sandboxes/:id/pty", s.createPTY)
- api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
- api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)
- api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
-
- // Templates
- api.POST("/templates", s.buildTemplate)
- api.GET("/templates", s.listTemplates)
- api.GET("/templates/:name", s.getTemplate)
- api.DELETE("/templates/:name", s.deleteTemplate)
- api.POST("/sandboxes/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)
+ // Data-plane routes: in server mode, proxy to workers; otherwise handle locally
+ if s.sandboxAPIProxy != nil {
+ // Server mode: proxy all data-plane requests to the worker that owns the sandbox
+ pxy := s.sandboxAPIProxy.ProxyHandler
+
+ // Exec
+ api.POST("/sandboxes/:id/exec", pxy)
+ api.GET("/sandboxes/:id/exec", pxy)
+ api.GET("/sandboxes/:id/exec/:sessionID", pxy)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", pxy)
+ api.POST("/sandboxes/:id/exec/run", pxy)
+
+ // Agent
+ api.POST("/sandboxes/:id/agent", pxy)
+ api.GET("/sandboxes/:id/agent", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/kill", pxy)
+
+ // Filesystem
+ api.GET("/sandboxes/:id/files", pxy)
+ api.PUT("/sandboxes/:id/files", pxy)
+ api.GET("/sandboxes/:id/files/list", pxy)
+ api.POST("/sandboxes/:id/files/mkdir", pxy)
+ api.DELETE("/sandboxes/:id/files", pxy)
+
+ // PTY
+ api.POST("/sandboxes/:id/pty", pxy)
+ api.GET("/sandboxes/:id/pty/:sessionID", pxy)
+ api.POST("/sandboxes/:id/pty/:sessionID/resize", pxy)
+ api.DELETE("/sandboxes/:id/pty/:sessionID", pxy)
+
+ // Timeout
+ api.POST("/sandboxes/:id/timeout", pxy)
+
+ // Token refresh
+ api.POST("/sandboxes/:id/token/refresh", pxy)
+ } else {
+ // Combined/worker mode: handle locally
+ api.POST("/sandboxes/:id/exec", s.createExecSession)
+ api.GET("/sandboxes/:id/exec", s.listExecSessions)
+ api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
+ api.POST("/sandboxes/:id/exec/run", s.execRun)
+
+ api.POST("/sandboxes/:id/agent", s.createAgentSession)
+ api.GET("/sandboxes/:id/agent", s.listAgentSessions)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
+ api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
+
+ api.GET("/sandboxes/:id/files", s.readFile)
+ api.PUT("/sandboxes/:id/files", s.writeFile)
+ api.GET("/sandboxes/:id/files/list", s.listDir)
+ api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
+ api.DELETE("/sandboxes/:id/files", s.removeFile)
+
+ api.POST("/sandboxes/:id/pty", s.createPTY)
+ api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
+ api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)
+ api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
+
+ api.POST("/sandboxes/:id/timeout", s.setTimeout)
+ }
+
+ // 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)
+ // Secret stores
+ api.POST("/secret-stores", s.createSecretStore)
+ api.GET("/secret-stores", s.listSecretStores)
+ api.GET("/secret-stores/:id", s.getSecretStore)
+ api.PUT("/secret-stores/:id", s.updateSecretStore)
+ api.DELETE("/secret-stores/:id", s.deleteSecretStore)
+
+ // Secret store entries
+ api.PUT("/secret-stores/:id/secrets/:name", s.setSecretEntry)
+ api.DELETE("/secret-stores/:id/secrets/:name", s.deleteSecretEntry)
+ api.GET("/secret-stores/:id/secrets", s.listSecretEntries)
+
// Workers (server mode only — queries worker registry)
api.GET("/workers", s.listWorkers)
diff --cc internal/api/sandbox.go
index 51869831,eae6289e..4c7c5e84
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@@ -60,42 -60,37 +60,73 @@@ func (s *Server) createSandbox(c echo.C
}
}
+ // Resolve secret store: decrypt secrets + inherit egress config
+ if cfg.SecretStore != "" && s.store != nil && hasOrg {
+ store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "secret store not found: " + cfg.SecretStore,
+ })
+ }
+
+ cfg.EgressAllowlist = store.EgressAllowlist
+
+ secrets, err := s.store.DecryptSecretEntries(ctx, store.ID)
+ if err != nil {
+ log.Printf("api: decrypt secrets failed for store %s: %v", cfg.SecretStore, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to decrypt secrets",
+ })
+ }
+ if len(secrets) > 0 {
+ if cfg.Envs == nil {
+ cfg.Envs = make(map[string]string)
+ }
+ for _, secret := range secrets {
+ if _, exists := cfg.Envs[secret.Name]; !exists {
+ cfg.Envs[secret.Name] = secret.Value
+ }
+ if len(secret.AllowedHosts) > 0 {
+ if cfg.SecretAllowedHosts == nil {
+ cfg.SecretAllowedHosts = make(map[string][]string)
+ }
+ cfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts
+ }
+ }
+ }
+ }
+
+ // 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 gRPC
if s.workerRegistry != nil {
return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)
diff --cc internal/db/migrations/015_projects.up.sql
index 065cf20a,00000000..065cf20a
mode 100644,000000..100644
--- a/internal/db/migrations/015_projects.up.sql
+++ b/internal/db/migrations/015_projects.up.sql
diff --cc internal/db/store.go
index 39dbad33,79ddd02f..cfd9e6b1
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@@ -85,7 -77,7 +85,8 @@@ func (s *Store) Migrate(ctx context.Con
{11, "migrations/011_rename_hibernation.up.sql"},
{12, "migrations/012_checkpoints.up.sql"},
{13, "migrations/013_checkpoint_patches.up.sql"},
- {14, "migrations/014_projects.up.sql"},
+ {14, "migrations/014_image_cache.up.sql"},
++ {15, "migrations/015_projects.up.sql"},
}
for _, m := range migrations {
diff --cc internal/firecracker/manager.go
index 997e9336,6bc15b70..cc08f7b0
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@@ -116,10 -93,9 +116,11 @@@ type Manager struct
nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)
uploadWg sync.WaitGroup // tracks in-flight async S3 uploads
- goldenMu sync.RWMutex
- golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
+ goldenMu sync.RWMutex
+ golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
+ templateGoldens map[string]*GoldenSnapshot // per-checkpoint golden snapshots for templates/images
+
+ secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configured
}
// NewManager creates a new Firecracker-backed sandbox manager.
diff --cc internal/worker/grpc_server.go
index 60632396,10a4d779..3d3abedf
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@@ -15,8 -15,10 +15,11 @@@ import
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/grpctls"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/sparse"
"github.com/opensandbox/opensandbox/internal/storage"
@@@ -70,9 -48,17 +72,8 @@@ func NewGRPCServer(mgr sandbox.Manager
execSessionManager: execMgr,
sandboxDBs: sandboxDBs,
checkpointStore: checkpointStore,
- builder: builder,
store: store,
- server: grpc.NewServer(
- grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
- MinTime: 5 * time.Second,
- PermitWithoutStream: true,
- }),
- grpc.KeepaliveParams(keepalive.ServerParameters{
- Time: 30 * time.Second,
- Timeout: 10 * time.Second,
- }),
- ),
+ server: grpc.NewServer(serverOpts...),
}
pb.RegisterSandboxWorkerServer(s.server, s)
return s
@@@ -92,37 -78,18 +93,38 @@@ func (s *GRPCServer) Stop()
s.server.GracefulStop()
}
+// parseSecretAllowedHosts converts the proto map (env var → comma-separated hosts)
+// to the internal map (env var → host slice). Returns nil if input is empty.
+func parseSecretAllowedHosts(m map[string]string) map[string][]string {
+ if len(m) == 0 {
+ return nil
+ }
+ result := make(map[string][]string, len(m))
+ for name, hosts := range m {
+ if hosts != "" {
+ result[name] = strings.Split(hosts, ",")
+ }
+ }
+ if len(result) == 0 {
+ return nil
+ }
+ return result
+}
+
func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxRequest) (*pb.CreateSandboxResponse, error) {
cfg := types.SandboxConfig{
- Template: req.Template,
- Timeout: int(req.Timeout),
- Envs: req.Envs,
- MemoryMB: int(req.MemoryMb),
- CpuCount: int(req.CpuCount),
- NetworkEnabled: req.NetworkEnabled,
- ImageRef: req.ImageRef,
- Port: int(req.Port),
- SandboxID: req.SandboxId, // use server-assigned ID if provided
- Template: req.Template,
- Timeout: int(req.Timeout),
- Envs: req.Envs,
- MemoryMB: int(req.MemoryMb),
- CpuCount: int(req.CpuCount),
- NetworkEnabled: req.NetworkEnabled,
- ImageRef: req.ImageRef,
- Port: int(req.Port),
- SandboxID: req.SandboxId, // use server-assigned ID if provided
- CheckpointID: req.CheckpointId, // for per-template golden snapshots
++ Template: req.Template,
++ Timeout: int(req.Timeout),
++ Envs: req.Envs,
++ MemoryMB: int(req.MemoryMb),
++ CpuCount: int(req.CpuCount),
++ NetworkEnabled: req.NetworkEnabled,
++ ImageRef: req.ImageRef,
++ Port: int(req.Port),
++ SandboxID: req.SandboxId, // use server-assigned ID if provided
++ CheckpointID: req.CheckpointId, // for per-template golden snapshots
+ EgressAllowlist: req.EgressAllowlist,
+ SecretAllowedHosts: parseSecretAllowedHosts(req.SecretAllowedHosts),
}
// Warm fork: if checkpoint_id is set, try snapshot-based fork first.
diff --cc pkg/types/sandbox.go
index b4d150d9,243520f9..8459ec21
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@@ -46,16 -49,12 +49,22 @@@ 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"`
+ // SecretStore name — resolves secrets from the named secret store.
+ SecretStore string `json:"secretStore,omitempty"`
+ // EgressAllowlist restricts outbound HTTPS from the sandbox to these hosts.
+ // Supports exact matches ("api.anthropic.com") and wildcards ("*.openai.com").
+ // Empty = all hosts allowed (no restriction).
+ EgressAllowlist []string `json:"egressAllowlist,omitempty"`
+ // SecretAllowedHosts maps env var name → allowed hosts for that secret.
+ // Secrets are only substituted in requests to matching hosts.
+ // Missing key or empty slice = substitute on all allowed hosts.
+ SecretAllowedHosts map[string][]string `json:"secretAllowedHosts,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 --cc sdks/python/opencomputer/__init__.py
index 796af156,a06bfd5b..24f2efe1
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@@ -4,9 -4,9 +4,11 @@@ from opencomputer.sandbox import Sandbo
from opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfo
from opencomputer.filesystem import Filesystem
from opencomputer.exec import Exec, ProcessResult, ExecSessionInfo
+ from opencomputer.image import Image
from opencomputer.pty import Pty, PtySession
+from opencomputer.template import Template
+from opencomputer.project import Project
+ from opencomputer.snapshot import Snapshots
__all__ = [
"Sandbox",
@@@ -18,10 -18,10 +20,12 @@@
"Exec",
"ProcessResult",
"ExecSessionInfo",
+ "Image",
"Pty",
"PtySession",
+ "Template",
+ "Project",
+ "Snapshots",
]
__version__ = "0.5.0"
diff --cc sdks/python/opencomputer/sandbox.py
index df8ffc32,4aac233e..a6000026
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@@ -37,7 -39,9 +39,10 @@@ class Sandbox
api_url: str | None = None,
envs: dict[str, str] | None = None,
metadata: dict[str, str] | None = None,
+ project: 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.
@@@ -46,10 -50,11 +51,13 @@@
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.
+ envs: Environment variables to inject. Overrides project secrets.
+ metadata: Custom metadata key-value pairs.
+ project: Project name — inherits template, cpu, memory, timeout,
+ and secrets from the project.
+ 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("/")
@@@ -72,12 -83,17 +86,19 @@@
body["envs"] = envs
if metadata:
body["metadata"] = metadata
+ if project:
+ body["project"] = project
-
- 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", "")
diff --cc sdks/typescript/src/index.ts
index 75041684,62315abd..c4167287
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@@ -3,5 -3,8 +3,10 @@@ export { Agent, type AgentEvent, type A
export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
+export { Templates, type TemplateInfo } from "./template.js";
+export { Project, type ProjectInfo, type ProjectOpts, type CreateProjectOpts, type UpdateProjectOpts } from "./project.js";
+ // Node.js-only modules (use crypto, fs, path) — import directly if needed:
+ // import { Image } from "@opencomputer/sdk/dist/image.js";
+ // import { Snapshots } from "@opencomputer/sdk/dist/snapshot.js";
+ export type { ImageManifest, ImageStep } from "./image.js";
+ export type { SnapshotInfo, CreateSnapshotOpts } from "./snapshot.js";
diff --cc sdks/typescript/src/sandbox.ts
index 2f99d868,83c7871b..b801681d
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@@ -17,8 -20,12 +20,14 @@@ export interface SandboxOpts
metadata?: Record<string, string>;
cpuCount?: number;
memoryMB?: number;
+ /** Project name — inherits template, cpu, memory, timeout, and secrets from the project. */
+ project?: string;
+ /** 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 {
@@@ -120,7 -127,18 +129,19 @@@ 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.project) body.project = opts.project;
+ 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",