An open-source, faster Devin alternative
TypeScript
fixes for prod 2, JWT TTL, routing, etc
Brian Reardon84749a5fae5c
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 202e76d7..7d0ae615 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -11,6 +11,7 @@ import ("github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/config"+ "github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/podman""github.com/opensandbox/opensandbox/internal/proxy"@@ -76,10 +77,28 @@ func main() {log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)}+ // Initialize PostgreSQL store for checkpoint lookups (auto-wake)+ var store *db.Store+ dbURL := cfg.DatabaseURL+ if dbURL == "" {+ dbURL = os.Getenv("DATABASE_URL")+ }+ if dbURL != "" {+ var err error+ store, err = db.NewStore(ctx, dbURL)+ if err != nil {+ log.Printf("opensandbox-worker: warning: failed to connect to database: %v (auto-wake disabled)", err)+ } else {+ defer store.Close()+ log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")+ }+ }+// Initialize SandboxRouter for rolling timeouts, auto-wake, and command routingsbRouter := sandbox.NewSandboxRouter(sandbox.RouterConfig{Manager: mgr,CheckpointStore: checkpointStore,+ Store: store,WorkerID: cfg.WorkerID,OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {log.Printf("opensandbox-worker: sandbox %s auto-hibernated (key=%s, size=%d bytes)",@@ -112,7 +131,7 @@ func main() {}// Start HTTP server for direct SDK access- httpServer := worker.NewHTTPServer(mgr, ptyMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter)+ httpServer := worker.NewHTTPServer(mgr, ptyMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain)httpAddr := fmt.Sprintf(":%d", cfg.Port)log.Printf("opensandbox-worker: starting HTTP server on %s", httpAddr)go func() {@@ -142,9 +161,11 @@ func main() {// Start Redis heartbeat for control plane discoveryif cfg.RedisURL != "" {- // On Fly.io, use the machine-specific internal address for gRPC+ // Determine the gRPC address to advertise to the control plane.grpcAdvertise := grpcAddr- if allocID := os.Getenv("FLY_ALLOC_ID"); allocID != "" {+ if addr := os.Getenv("OPENSANDBOX_GRPC_ADVERTISE"); addr != "" {+ grpcAdvertise = addr+ } else if allocID := os.Getenv("FLY_ALLOC_ID"); allocID != "" {grpcAdvertise = allocID + ".vm.opensandbox-worker.internal:9090"}diff --git a/deploy/Dockerfile.worker b/deploy/Dockerfile.workerindex 55a8880a..7b6bf4c7 100644--- a/deploy/Dockerfile.worker+++ b/deploy/Dockerfile.worker@@ -7,19 +7,129 @@ RUN go mod downloadCOPY . .RUN CGO_ENABLED=1 go build -o /opensandbox-worker ./cmd/worker-FROM ubuntu:22.04+# Build CRIU from source (Ubuntu 24.04 doesn't ship CRIU in repos)+FROM ubuntu:24.04 AS criu-builder++RUN apt-get update && apt-get install -y --no-install-recommends \+ git \+ gcc \+ make \+ automake \+ autoconf \+ libtool \+ pkg-config \+ libprotobuf-dev \+ libprotobuf-c-dev \+ protobuf-c-compiler \+ protobuf-compiler \+ python3 \+ python3-protobuf \+ python3-yaml \+ libbsd-dev \+ iproute2 \+ libcap-dev \+ libnl-3-dev \+ libnet-dev \+ libaio-dev \+ libgnutls28-dev \+ ca-certificates \+ && rm -rf /var/lib/apt/lists/*++RUN git clone --depth 1 --branch v4.0 https://github.com/checkpoint-restore/criu.git /criu+WORKDIR /criu+RUN make -j$(nproc) && make install-criu install-lib PREFIX=/usr/local LIBDIR=/usr/local/lib++# Build crun from source with CRIU checkpoint support+FROM ubuntu:24.04 AS crun-builder++RUN apt-get update && apt-get install -y --no-install-recommends \+ git \+ gcc \+ make \+ automake \+ autoconf \+ libtool \+ pkg-config \+ libsystemd-dev \+ libcap-dev \+ libseccomp-dev \+ libyajl-dev \+ libprotobuf-c-dev \+ python3 \+ go-md2man \+ ca-certificates \+ && rm -rf /var/lib/apt/lists/*++# Copy CRIU headers and libs so crun can compile with --with-criu+COPY --from=criu-builder /usr/local/include/criu /usr/local/include/criu+COPY --from=criu-builder /usr/local/lib/libcriu.so* /usr/local/lib/++# Create pkg-config file for criu (CRIU 4.0)+RUN mkdir -p /usr/local/lib/pkgconfig && \+ printf 'prefix=/usr/local\nlibdir=${prefix}/lib\nincludedir=${prefix}/include\nName: criu\nDescription: CRIU library\nVersion: 4.0\nLibs: -L${libdir} -lcriu\nCflags: -I${includedir}\n' \+ > /usr/local/lib/pkgconfig/criu.pc++RUN ldconfig++RUN git clone --depth 1 --branch 1.19.1 https://github.com/containers/crun.git /crun+WORKDIR /crun+RUN ./autogen.sh && PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./configure --with-criu && make -j$(nproc)++# Runtime: Ubuntu 24.04 gives us Podman 4.9+ with proper maskedPaths handling for CRIU+FROM ubuntu:24.04RUN apt-get update && apt-get install -y --no-install-recommends \podman \- crun \- criu \uidmap \fuse-overlayfs \slirp4netns \ca-certificates \+ libyajl2 \+ libseccomp2 \+ libsystemd0 \+ libprotobuf-c1 \+ libnl-3-200 \+ libnet1 \+ libbsd0 \+ libgnutls30t64 \+ iproute2 \&& rm -rf /var/lib/apt/lists/*+# Install our source-built CRIU and crun+COPY --from=criu-builder /usr/local/sbin/criu /usr/local/sbin/criu+COPY --from=criu-builder /usr/local/lib/libcriu.so* /usr/local/lib/+COPY --from=crun-builder /crun/crun /usr/bin/crun+RUN ldconfig++# Configure podman to use cgroupfs (Fly VMs use cgroup v1 without systemd)+RUN mkdir -p /etc/containers && \+ printf '[engine]\ncgroup_manager = "cgroupfs"\nevents_logger = "file"\n' \+ > /etc/containers/containers.conf+COPY --from=builder /opensandbox-worker /usr/local/bin/opensandbox-worker+# Entrypoint script fixes cgroup v1 symlinks on Fly.io before starting the worker.+# Fly VMs mount "cpu,cpuacct" as the real cgroup controller but leave "cpu" as a+# plain empty directory instead of a symlink. This breaks podman resource limits.+RUN printf '#!/bin/sh\nset -e\n\+# Ensure cgroup v1 combined controllers have single-name symlinks.\n\+# Fly VMs may mount "cpu,cpuacct" without a "cpu" symlink, or leave\n\+# "cpu" as an empty plain directory. Either case breaks podman.\n\+fix_cgroup() {\n\+ combined="/sys/fs/cgroup/$2"\n\+ single="/sys/fs/cgroup/$1"\n\+ [ -d "$combined" ] || return 0\n\+ if [ -L "$single" ]; then return 0; fi\n\+ rm -rf "$single" 2>/dev/null || true\n\+ ln -s "$combined" "$single"\n\+}\n\+fix_cgroup cpu cpu,cpuacct\n\+fix_cgroup cpuacct cpu,cpuacct\n\+fix_cgroup net_cls net_cls,net_prio\n\+fix_cgroup net_prio net_cls,net_prio\n\+exec "$@"\n' > /usr/local/bin/worker-entrypoint.sh && \+ chmod +x /usr/local/bin/worker-entrypoint.sh+EXPOSE 8080 9090 9091+ENTRYPOINT ["worker-entrypoint.sh"]CMD ["opensandbox-worker"]diff --git a/deploy/worker-entrypoint.sh b/deploy/worker-entrypoint.shnew file mode 100755index 00000000..23f88ecb--- /dev/null+++ b/deploy/worker-entrypoint.sh@@ -0,0 +1,38 @@+#!/bin/sh+set -e++# Fix cgroup v1 split controller directories on Fly.io VMs.+#+# Fly VMs mount cgroup v1 controllers as separate directories like+# "cpu,cpuacct" and "net_cls,net_prio". On standard Linux systems,+# "cpu" is a symlink to "cpu,cpuacct", but Fly creates "cpu" as+# a plain (empty) directory. This breaks podman/crun because they+# try to create cgroup paths under /sys/fs/cgroup/cpu/ which is+# not a real cgroup filesystem — just an empty tmpfs directory.+#+# Fix: replace the plain directories with symlinks to the real+# combined controller directories.++fix_cgroup_symlink() {+ local single="$1" # e.g. "cpu"+ local combined="$2" # e.g. "cpu,cpuacct"++ combined_path="/sys/fs/cgroup/${combined}"+ single_path="/sys/fs/cgroup/${single}"++ # Only fix if the combined path exists and the single path+ # is a directory (not already a symlink)+ if [ -d "$combined_path" ] && [ -d "$single_path" ] && [ ! -L "$single_path" ]; then+ echo "entrypoint: fixing cgroup symlink ${single} -> ${combined}"+ rm -rf "$single_path"+ ln -s "$combined_path" "$single_path"+ fi+}++# Fix known split cgroup v1 controllers+fix_cgroup_symlink "cpu" "cpu,cpuacct"+fix_cgroup_symlink "cpuacct" "cpu,cpuacct"+fix_cgroup_symlink "net_cls" "net_cls,net_prio"+fix_cgroup_symlink "net_prio" "net_cls,net_prio"++exec "$@"diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex b80ae13d..fc1280f5 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -75,13 +75,9 @@ func (s *Server) createSandbox(c echo.Context) error {}}- // Issue sandbox-scoped JWT for combined mode+ // Issue sandbox-scoped JWT for combined mode (24h TTL — independent of sandbox idle timeout)if s.jwtIssuer != nil {- timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300- }- token, err := s.jwtIssuer.IssueSandboxToken(orgID, sb.ID, s.workerID, time.Duration(timeout)*time.Second)+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, sb.ID, s.workerID, 24*time.Hour)if err == nil {sb.Token = token}@@ -133,7 +129,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty}// Dispatch via persistent gRPC connection- grpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ grpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)defer cancel()grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{@@ -150,14 +146,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty})}- // Issue sandbox-scoped JWT- timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300- }+ // Issue sandbox-scoped JWT (24h TTL — independent of sandbox idle timeout)var token stringif s.jwtIssuer != nil {- t, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, time.Duration(timeout)*time.Second)+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, 24*time.Hour)if err != nil {log.Printf("sandbox: failed to issue JWT: %v", err)} else {@@ -636,11 +628,7 @@ func (s *Server) wakeSandbox(c echo.Context) error {// Issue fresh JWTorgID, _ := auth.GetOrgID(c)if s.jwtIssuer != nil {- timeout := req.Timeout- if timeout <= 0 {- timeout = 300- }- token, err := s.jwtIssuer.IssueSandboxToken(orgID, id, s.workerID, time.Duration(timeout)*time.Second)+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, id, s.workerID, 24*time.Hour)if err == nil {sb.Token = token}@@ -709,7 +697,7 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W}var token stringif s.jwtIssuer != nil {- t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, worker.ID, time.Duration(timeout)*time.Second)+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, worker.ID, 24*time.Hour)if err == nil {token = t}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex d424ada7..c9b93ae3 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -10,7 +10,9 @@ import ("github.com/redis/go-redis/v9""google.golang.org/grpc"+ "google.golang.org/grpc/connectivity""google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/keepalive"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -207,9 +209,29 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s)", entry.ID, entry.Region, entry.GRPCAddr)}- // Ensure gRPC connection exists- if _, hasConn := r.conns[entry.ID]; !hasConn && entry.GRPCAddr != "" {- r.dialWorkerLocked(entry.ID, entry.GRPCAddr)+ // Ensure gRPC connection exists and is healthy.+ // Re-dial if address changed OR connection is in a failed state.+ if entry.GRPCAddr != "" {+ if conn, hasConn := r.conns[entry.ID]; hasConn {+ addrChanged := existing != nil && existing.GRPCAddr != entry.GRPCAddr+ state := conn.GetState()+ connDead := state == connectivity.TransientFailure || state == connectivity.Shutdown+ if addrChanged || connDead {+ if addrChanged {+ log.Printf("redis_registry: worker %s gRPC address changed (%s → %s), re-dialing",+ entry.ID, existing.GRPCAddr, entry.GRPCAddr)+ } else {+ log.Printf("redis_registry: worker %s gRPC connection in %s state, re-dialing",+ entry.ID, conn.GetState().String())+ }+ conn.Close()+ delete(r.conns, entry.ID)+ delete(r.clients, entry.ID)+ r.dialWorkerLocked(entry.ID, entry.GRPCAddr)+ }+ } else {+ r.dialWorkerLocked(entry.ID, entry.GRPCAddr)+ }}}@@ -217,14 +239,23 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {conn, err := grpc.NewClient(grpcAddr,grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 10 * time.Second,+ Timeout: 5 * time.Second,+ PermitWithoutStream: true,+ }),)if err != nil {log.Printf("redis_registry: failed to dial gRPC for worker %s at %s: %v", workerID, grpcAddr, err)return}+ // Force the lazy connection to start connecting immediately.+ // Without this, grpc.NewClient stays IDLE until the first RPC,+ // which means keepalive can't detect a dead connection.+ conn.Connect()r.conns[workerID] = connr.clients[workerID] = pb.NewSandboxWorkerClient(conn)- log.Printf("redis_registry: gRPC connection established to worker %s at %s", workerID, grpcAddr)+ log.Printf("redis_registry: gRPC connection initiated to worker %s at %s", workerID, grpcAddr)}// GetLeastLoadedWorker returns the worker with the most remaining capacity.diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 5294d9eb..be5623ae 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -154,12 +154,8 @@ func (s *Server) createSandbox(c echo.Context) error {metadataJSON, _ := json.Marshal(req.Metadata)_, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)- // Issue sandbox-scoped JWT- timeout := req.Timeout- if timeout <= 0 {- timeout = 300- }- token, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, time.Duration(timeout)*time.Second)+ // Issue sandbox-scoped JWT (24h TTL — independent of sandbox idle timeout)+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, 24*time.Hour)if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to issue token"})}diff --git a/internal/podman/client.go b/internal/podman/client.goindex cd93bf4b..58255a5f 100644--- a/internal/podman/client.go+++ b/internal/podman/client.go@@ -12,7 +12,6 @@ import ("path/filepath""runtime""strings"- "syscall")// Client wraps the podman CLI for container operations.@@ -151,7 +150,7 @@ func (c *Client) runSSH(ctx context.Context, sshCmd string) (*ExecResult, error)func (c *Client) CheckpointContainer(ctx context.Context, nameOrID, exportPath string) error {if c.useSSH {// exportPath is a VM-local path (e.g. /tmp/...) since we'll copy it out separately- sshCmd := fmt.Sprintf("podman container checkpoint --export %s --compress zstd %s", exportPath, nameOrID)+ sshCmd := fmt.Sprintf("podman container checkpoint --tcp-established --export %s --compress zstd %s", exportPath, nameOrID)result, err := c.runSSH(ctx, sshCmd)if err != nil {return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)@@ -162,7 +161,7 @@ func (c *Client) CheckpointContainer(ctx context.Context, nameOrID, exportPath sreturn nil}- result, err := c.Run(ctx, "container", "checkpoint", "--export", exportPath, "--compress", "zstd", nameOrID)+ result, err := c.Run(ctx, "container", "checkpoint", "--tcp-established", "--export", exportPath, "--compress", "zstd", nameOrID)if err != nil {return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)}@@ -174,9 +173,15 @@ func (c *Client) CheckpointContainer(ctx context.Context, nameOrID, exportPath s// RestoreContainer restores a container from a checkpoint archive on disk.// On macOS, restore runs inside the Podman machine VM via SSH.+// It force-removes any existing container with the same name first to avoid+// "that ID is already in use" errors from previous restore cycles.func (c *Client) RestoreContainer(ctx context.Context, importPath, name string) error {+ // Pre-cleanup: remove any existing container with this name to avoid ID conflicts.+ // This is best-effort — the container may not exist, which is fine.+ _ = c.RemoveContainer(ctx, name, true)+if c.useSSH {- sshCmd := fmt.Sprintf("podman container restore --import %s --name %s", importPath, name)+ sshCmd := fmt.Sprintf("podman container restore --tcp-established --import %s", importPath)result, err := c.runSSH(ctx, sshCmd)if err != nil {return fmt.Errorf("failed to restore container %s: %w", name, err)@@ -187,7 +192,7 @@ func (c *Client) RestoreContainer(ctx context.Context, importPath, name string)return nil}- result, err := c.Run(ctx, "container", "restore", "--import", importPath, "--name", name)+ result, err := c.Run(ctx, "container", "restore", "--tcp-established", "--import", importPath)if err != nil {return fmt.Errorf("failed to restore container %s: %w", name, err)}@@ -274,36 +279,21 @@ func (c *Client) RestoreContainerFromStream(ctx context.Context, reader io.Readereturn c.RestoreContainer(ctx, vmPath, name)}- tmpDir, err := os.MkdirTemp("", "osb-restore-")+ // Download to temp file, then restore from file+ tmpFile, err := os.CreateTemp("", "osb-restore-*.tar.zst")if err != nil {- return fmt.Errorf("failed to create temp dir: %w", err)- }- defer os.RemoveAll(tmpDir)-- fifoPath := filepath.Join(tmpDir, "checkpoint.tar.zst")- if err := syscall.Mkfifo(fifoPath, 0600); err != nil {- return fmt.Errorf("failed to create FIFO: %w", err)+ return fmt.Errorf("failed to create temp file: %w", err)}+ localPath := tmpFile.Name()+ defer os.Remove(localPath)- // Start podman restore reading from the FIFO (blocks until data is available)- errCh := make(chan error, 1)- go func() {- errCh <- c.RestoreContainer(ctx, fifoPath, name)- }()-- // Open FIFO for writing and copy stream data into it- fifo, err := os.OpenFile(fifoPath, os.O_WRONLY, 0)- if err != nil {- return fmt.Errorf("failed to open FIFO for writing: %w", err)- }- if _, err := io.Copy(fifo, reader); err != nil {- fifo.Close()- return fmt.Errorf("failed to stream checkpoint to FIFO: %w", err)+ if _, err := io.Copy(tmpFile, reader); err != nil {+ tmpFile.Close()+ return fmt.Errorf("failed to write checkpoint to temp file: %w", err)}- fifo.Close() // Signal EOF to podman+ tmpFile.Close()- // Wait for podman restore to complete- return <-errCh+ return c.RestoreContainer(ctx, localPath, name)}// FindFreePort asks the OS for a free TCP port by listening on :0.diff --git a/internal/podman/container.go b/internal/podman/container.goindex bfc56533..10f17843 100644--- a/internal/podman/container.go+++ b/internal/podman/container.go@@ -42,7 +42,7 @@ func DefaultContainerConfig(name, image string) ContainerConfig {ReadOnly: false,TmpFS: map[string]string{},CapDrop: []string{"ALL"},- SecurityOpts: []string{"no-new-privileges"},+ SecurityOpts: []string{},UserNS: "",Entrypoint: []string{"/bin/sleep"},Command: []string{"infinity"},diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex 8f742d3b..693e8296 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -1,12 +1,16 @@package workerimport (+ "context""io""net/http""time"+ "github.com/google/uuid""github.com/gorilla/websocket""github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/pkg/types")@@ -65,14 +69,27 @@ func (s *HTTPServer) runCommand(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})}+ var result *types.ProcessResult+ var execErr errorstart := time.Now()- result, err := s.manager.Exec(c.Request().Context(), id, cfg)- durationMs := int(time.Since(start).Milliseconds())- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ routeOp := func(ctx context.Context) error {+ result, execErr = s.manager.Exec(ctx, id, cfg)+ return execErr}+ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "exec", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ }++ durationMs := int(time.Since(start).Milliseconds())+// Log command to per-sandbox SQLiteif s.sandboxDBs != nil {sdb, dbErr := s.sandboxDBs.Get(id)@@ -90,10 +107,24 @@ func (s *HTTPServer) readFile(c echo.Context) error {if path == "" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- content, err := s.manager.ReadFile(c.Request().Context(), id, path)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})++ var content string+ routeOp := func(ctx context.Context) error {+ var err error+ content, err = s.manager.ReadFile(ctx, id, path)+ return err}++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "readFile", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ }+return c.String(http.StatusOK, content)}@@ -107,9 +138,21 @@ func (s *HTTPServer) writeFile(c echo.Context) error {if err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "failed to read request body: " + err.Error()})}- if err := s.manager.WriteFile(c.Request().Context(), id, path, string(body)); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})++ routeOp := func(ctx context.Context) error {+ return s.manager.WriteFile(ctx, id, path, string(body))+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "writeFile", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }}+return c.NoContent(http.StatusNoContent)}@@ -119,10 +162,24 @@ func (s *HTTPServer) listDir(c echo.Context) error {if path == "" {path = "/"}- entries, err := s.manager.ListDir(c.Request().Context(), id, path)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})++ var entries []types.EntryInfo+ routeOp := func(ctx context.Context) error {+ var err error+ entries, err = s.manager.ListDir(ctx, id, path)+ return err+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "listDir", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }}+return c.JSON(http.StatusOK, entries)}@@ -132,9 +189,21 @@ func (s *HTTPServer) makeDir(c echo.Context) error {if path == "" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- if err := s.manager.MakeDir(c.Request().Context(), id, path); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})++ routeOp := func(ctx context.Context) error {+ return s.manager.MakeDir(ctx, id, path)}++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "makeDir", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ }+return c.NoContent(http.StatusNoContent)}@@ -144,9 +213,21 @@ func (s *HTTPServer) removeFile(c echo.Context) error {if path == "" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- if err := s.manager.Remove(c.Request().Context(), id, path); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})++ routeOp := func(ctx context.Context) error {+ return s.manager.Remove(ctx, id, path)+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "removeFile", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }}+return c.NoContent(http.StatusNoContent)}@@ -158,9 +239,21 @@ func (s *HTTPServer) createPTY(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})}- session, err := s.ptyManager.CreateSession(id, req)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ var session *sandbox.PTYSessionHandle+ routeOp := func(ctx context.Context) error {+ var err error+ session, err = s.ptyManager.CreateSession(id, req)+ return err+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "createPTY", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }}// Log PTY start to SQLite@@ -178,6 +271,7 @@ func (s *HTTPServer) createPTY(c echo.Context) error {}func (s *HTTPServer) ptyWebSocket(c echo.Context) error {+ id := c.Param("id")sessionID := c.Param("sessionID")session, err := s.ptyManager.GetSession(sessionID)@@ -185,6 +279,11 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})}+ // Touch to reset rolling timeout when PTY connects+ if s.router != nil {+ s.router.Touch(id)+ }+ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)if err != nil {return err@@ -198,6 +297,10 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {for {n, err := session.PTY.Read(buf)if n > 0 {+ // Touch on PTY output to keep sandbox alive+ if s.router != nil {+ s.router.Touch(id)+ }if writeErr := ws.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {return}@@ -214,6 +317,10 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {if err != nil {return}+ // Touch on PTY input to keep sandbox alive+ if s.router != nil {+ s.router.Touch(id)+ }if _, err := session.PTY.Write(msg); err != nil {return}@@ -233,11 +340,49 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {}func (s *HTTPServer) killPTY(c echo.Context) error {+ id := c.Param("id")sessionID := c.Param("sessionID")- if err := s.ptyManager.KillSession(sessionID); err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ routeOp := func(ctx context.Context) error {+ return s.ptyManager.KillSession(sessionID)+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "killPTY", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ } else {+ if err := routeOp(c.Request().Context()); err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }}return c.NoContent(http.StatusNoContent)}++// refreshToken issues a fresh 24h JWT for a sandbox.+// The caller must already be authenticated (existing valid JWT via middleware).+func (s *HTTPServer) refreshToken(c echo.Context) error {+ sandboxID := c.Param("id")++ orgIDVal := c.Get(string(auth.ContextKeyOrgID))+ orgID, _ := orgIDVal.(uuid.UUID)+ workerID, _ := c.Get("worker_id").(string)++ if s.jwtIssuer == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "JWT issuer not configured",+ })+ }++ token, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 24*time.Hour)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to issue token: " + err.Error(),+ })+ }++ return c.JSON(http.StatusOK, map[string]string{+ "token": token,+ })+}diff --git a/internal/worker/http_server.go b/internal/worker/http_server.goindex bec550ef..4485757d 100644--- a/internal/worker/http_server.go+++ b/internal/worker/http_server.go@@ -2,6 +2,7 @@ package workerimport ("net/http"+ "strings""github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware"@@ -13,27 +14,29 @@ import (// HTTPServer serves the REST/WebSocket API for direct SDK access on the worker.// It exposes the same endpoints as the control plane but authenticates via sandbox-scoped JWTs.type HTTPServer struct {- echo *echo.Echo- manager *sandbox.Manager- ptyManager *sandbox.PTYManager- jwtIssuer *auth.JWTIssuer- sandboxDBs *sandbox.SandboxDBManager- router *sandbox.SandboxRouter+ echo *echo.Echo+ manager *sandbox.Manager+ ptyManager *sandbox.PTYManager+ jwtIssuer *auth.JWTIssuer+ sandboxDBs *sandbox.SandboxDBManager+ router *sandbox.SandboxRouter+ sandboxDomain string}// NewHTTPServer creates a new worker HTTP server for direct SDK access.-func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter) *HTTPServer {+func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {e := echo.New()e.HideBanner = truee.HidePort = trues := &HTTPServer{- echo: e,- manager: mgr,- ptyManager: ptyMgr,- jwtIssuer: jwtIssuer,- sandboxDBs: sandboxDBs,- router: sbRouter,+ echo: e,+ manager: mgr,+ ptyManager: ptyMgr,+ jwtIssuer: jwtIssuer,+ sandboxDBs: sandboxDBs,+ router: sbRouter,+ sandboxDomain: sandboxDomain,}// Global middleware@@ -52,6 +55,23 @@ func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *return c.JSON(http.StatusOK, map[string]string{"status": "ok", "role": "worker"})})+ // Caddy on-demand TLS check — validates that a domain is a valid sandbox subdomain+ e.GET("/caddy/check", func(c echo.Context) error {+ domain := c.QueryParam("domain")+ if domain == "" {+ return c.String(http.StatusForbidden, "missing domain")+ }+ suffix := "." + s.sandboxDomain+ if !strings.HasSuffix(domain, suffix) {+ return c.String(http.StatusForbidden, "invalid domain")+ }+ sub := strings.TrimSuffix(domain, suffix)+ if sub == "" || strings.Contains(sub, ".") {+ return c.String(http.StatusForbidden, "invalid subdomain")+ }+ return c.String(http.StatusOK, "ok")+ })+// All sandbox routes require JWT authapi := e.Group("")api.Use(auth.SandboxJWTMiddleware(jwtIssuer))@@ -72,6 +92,9 @@ func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *api.POST("/sandboxes/:id/files/mkdir", s.makeDir)api.DELETE("/sandboxes/:id/files", s.removeFile)+ // Token refresh+ api.POST("/sandboxes/:id/token/refresh", s.refreshToken)+// PTYapi.POST("/sandboxes/:id/pty", s.createPTY)api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)diff --git a/opensandbox-worker b/opensandbox-workernew file mode 100755index 00000000..c90c80bbBinary files /dev/null and b/opensandbox-worker differdiff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.tsnew file mode 100644index 00000000..ea3b9df7--- /dev/null+++ b/sdks/typescript/examples/run-all-tests.ts@@ -0,0 +1,128 @@+/**+ * OpenSandbox Production Test Suite Runner+ *+ * Runs all production tests in sequence, with a summary at the end.+ * Tests are ordered from fast/simple to slow/complex.+ *+ * Usage:+ * npx tsx examples/run-all-tests.ts # Run all tests+ * npx tsx examples/run-all-tests.ts --skip-slow # Skip timeout test (waits ~2min)+ *+ * Individual tests:+ * npx tsx examples/test-python-sdk.ts+ * npx tsx examples/test-multi-template.ts+ * npx tsx examples/test-commands.ts+ * npx tsx examples/test-file-ops.ts+ * npx tsx examples/test-reconnect.ts+ * npx tsx examples/test-domain-tls.ts+ * npx tsx examples/test-concurrent.ts+ * npx tsx examples/test-hibernation-stress.ts+ * npx tsx examples/test-timeout.ts+ * npx tsx examples/webhook-demo.ts+ */++import { execSync } from "child_process";+import * as path from "path";++const BOLD = "\x1b[1m";+const GREEN = "\x1b[32m";+const RED = "\x1b[31m";+const DIM = "\x1b[2m";+const RESET = "\x1b[0m";+const CYAN = "\x1b[36m";++const skipSlow = process.argv.includes("--skip-slow");++interface TestSuite {+ name: string;+ file: string;+ slow?: boolean;+ description: string;+}++const SUITES: TestSuite[] = [+ { name: "Commands", file: "test-commands.ts", description: "Shell commands, stderr, exit codes, pipes, concurrency" },+ { name: "File Ops", file: "test-file-ops.ts", description: "Large files, special chars, nested dirs, deletion" },+ { name: "Python SDK", file: "test-python-sdk.ts", description: "Python template, stdlib, file ops from Python" },+ { name: "Multi-Template", file: "test-multi-template.ts", description: "base, python, node templates" },+ { name: "Reconnect", file: "test-reconnect.ts", description: "Sandbox.connect(), state persistence, multi-conn" },+ { name: "Domain/TLS", file: "test-domain-tls.ts", description: "Subdomains, Let's Encrypt certs, routing isolation" },+ { name: "Concurrent", file: "test-concurrent.ts", description: "5 sandboxes in parallel, isolation, parallel ops" },+ { name: "Hibernation", file: "test-hibernation-stress.ts", description: "Multi-cycle hibernate/wake, large state, auto-wake" },+ { name: "Timeout", file: "test-timeout.ts", slow: true, description: "30s timeout, setTimeout(), rolling timeout (takes ~2min)" },+];++async function main() {+ console.log(`${BOLD}\n╔════════════════════════════════════════════════════════╗`);+ console.log(`║ OpenSandbox Production Test Suite ║`);+ console.log(`╚════════════════════════════════════════════════════════╝${RESET}\n`);++ const filteredSuites = skipSlow ? SUITES.filter(s => !s.slow) : SUITES;++ console.log(`${DIM}Running ${filteredSuites.length} test suites${skipSlow ? " (slow tests skipped)" : ""}${RESET}`);+ console.log(`${DIM}${"─".repeat(60)}${RESET}\n`);++ const results: { name: string; passed: boolean; durationMs: number; error?: string }[] = [];+ const totalStart = Date.now();++ for (let i = 0; i < filteredSuites.length; i++) {+ const suite = filteredSuites[i];+ const filePath = path.join(__dirname, suite.file);++ console.log(`${BOLD}[${i + 1}/${filteredSuites.length}] ${suite.name}${RESET}`);+ console.log(`${DIM} ${suite.description}${RESET}`);+ console.log(`${DIM} Running: npx tsx ${suite.file}${RESET}\n`);++ const start = Date.now();+ try {+ execSync(`npx tsx "${filePath}"`, {+ stdio: "inherit",+ env: { ...process.env },+ timeout: 300000, // 5 min max per suite+ });+ const durationMs = Date.now() - start;+ results.push({ name: suite.name, passed: true, durationMs });+ console.log(`${GREEN}── ${suite.name}: PASSED (${(durationMs / 1000).toFixed(1)}s) ──${RESET}\n`);+ } catch (err: any) {+ const durationMs = Date.now() - start;+ results.push({ name: suite.name, passed: false, durationMs, error: err.message });+ console.log(`${RED}── ${suite.name}: FAILED (${(durationMs / 1000).toFixed(1)}s) ──${RESET}\n`);+ }+ }++ const totalMs = Date.now() - totalStart;++ // ── Summary ─────────────────────────────────────────────────────────+ console.log(`\n${BOLD}╔════════════════════════════════════════════════════════╗`);+ console.log(`║ Test Results ║`);+ console.log(`╠════════════════════════════════════════════════════════╣${RESET}`);++ const maxNameLen = Math.max(...results.map(r => r.name.length));+ for (const r of results) {+ const icon = r.passed ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;+ const name = r.name.padEnd(maxNameLen);+ const duration = `${(r.durationMs / 1000).toFixed(1)}s`.padStart(7);+ console.log(` ${icon} ${name} ${duration}`);+ }++ const passedCount = results.filter(r => r.passed).length;+ const failedCount = results.filter(r => !r.passed).length;++ console.log(`${BOLD}\n╠════════════════════════════════════════════════════════╣`);+ console.log(`║ ${passedCount} passed, ${failedCount} failed | Total: ${(totalMs / 1000).toFixed(1)}s${" ".repeat(Math.max(0, 32 - String(passedCount).length - String(failedCount).length - String((totalMs / 1000).toFixed(1)).length))}║`);+ console.log(`╚════════════════════════════════════════════════════════╝${RESET}\n`);++ if (failedCount > 0) {+ console.log(`${RED}Failed suites:${RESET}`);+ for (const r of results.filter(r => !r.passed)) {+ console.log(` ${RED}✗ ${r.name}${RESET}`);+ }+ console.log();+ process.exit(1);+ }+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/sdks/typescript/examples/test-commands.ts b/sdks/typescript/examples/test-commands.tsnew file mode 100644index 00000000..1d39a702--- /dev/null+++ b/sdks/typescript/examples/test-commands.ts@@ -0,0 +1,236 @@+/**+ * Command Edge Cases Test+ *+ * Tests:+ * 1. Long-running command with timeout+ * 2. Command that writes to stderr+ * 3. Non-zero exit codes+ * 4. Large stdout output+ * 5. Environment variable passing+ * 6. Working directory+ * 7. Pipe and shell features+ * 8. Concurrent commands on same sandbox+ *+ * Usage:+ * npx tsx examples/test-commands.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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("║ Command Edge Cases Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ let sandbox: Sandbox | null = null;++ try {+ sandbox = await Sandbox.create({ template: "base", timeout: 120 });+ green(`Created sandbox: ${sandbox.sandboxId}`);+ console.log();++ // ── Test 1: Basic command ───────────────────────────────────────+ bold("━━━ Test 1: Basic commands ━━━\n");++ const echo = await sandbox.commands.run("echo hello-world");+ check("Echo returns correct output", echo.stdout.trim() === "hello-world");+ check("Echo exit code is 0", echo.exitCode === 0);++ const multi = await sandbox.commands.run("echo line1 && echo line2 && echo line3");+ const lines = multi.stdout.trim().split("\n");+ check("Multi-command outputs 3 lines", lines.length === 3);+ check("Multi-command content correct", lines[0] === "line1" && lines[2] === "line3");+ console.log();++ // ── Test 2: stderr handling ─────────────────────────────────────+ bold("━━━ Test 2: stderr handling ━━━\n");++ const stderrCmd = await sandbox.commands.run("echo error-msg >&2");+ check("stderr captured", stderrCmd.stderr.trim() === "error-msg");+ check("stdout empty when writing to stderr", stderrCmd.stdout.trim() === "");+ check("Exit code 0 even with stderr", stderrCmd.exitCode === 0);++ // Mixed stdout + stderr+ const mixed = await sandbox.commands.run("echo stdout-data && echo stderr-data >&2");+ check("Mixed: stdout captured", mixed.stdout.includes("stdout-data"));+ check("Mixed: stderr captured", mixed.stderr.includes("stderr-data"));+ console.log();++ // ── Test 3: Non-zero exit codes ─────────────────────────────────+ bold("━━━ Test 3: Non-zero exit codes ━━━\n");++ const exit1 = await sandbox.commands.run("exit 1");+ check("Exit code 1 captured", exit1.exitCode === 1, `got ${exit1.exitCode}`);++ const exit42 = await sandbox.commands.run("exit 42");+ check("Exit code 42 captured", exit42.exitCode === 42, `got ${exit42.exitCode}`);++ const falseCmd = await sandbox.commands.run("false");+ check("'false' returns exit code 1", falseCmd.exitCode === 1, `got ${falseCmd.exitCode}`);++ const notFound = await sandbox.commands.run("nonexistent-command-xyz 2>&1 || true");+ check("Non-existent command handled", notFound.exitCode === 0);+ console.log();++ // ── Test 4: Large stdout ────────────────────────────────────────+ bold("━━━ Test 4: Large stdout output ━━━\n");++ // Generate ~100KB of output+ const largeOut = await sandbox.commands.run("seq 1 10000");+ const lineCount = largeOut.stdout.trim().split("\n").length;+ check("10000 lines of output captured", lineCount === 10000, `got ${lineCount} lines`);+ dim(`Output size: ${largeOut.stdout.length} chars`);++ // Verify first and last+ const largeLines = largeOut.stdout.trim().split("\n");+ check("First line is 1", largeLines[0] === "1");+ check("Last line is 10000", largeLines[lineCount - 1] === "10000");+ console.log();++ // ── Test 5: Environment variables ───────────────────────────────+ bold("━━━ Test 5: Environment variable passing ━━━\n");++ const envResult = await sandbox.commands.run("echo $MY_VAR", {+ env: { MY_VAR: "secret-value-123" },+ });+ check("Env var passed correctly", envResult.stdout.trim() === "secret-value-123");++ // Multiple env vars+ const multiEnv = await sandbox.commands.run('echo "$A:$B:$C"', {+ env: { A: "alpha", B: "beta", C: "gamma" },+ });+ check("Multiple env vars", multiEnv.stdout.trim() === "alpha:beta:gamma");++ // Env var with special characters+ const specialEnv = await sandbox.commands.run("echo $SPECIAL", {+ env: { SPECIAL: "hello world with spaces & stuff" },+ });+ check("Env var with special chars", specialEnv.stdout.trim() === "hello world with spaces & stuff");+ console.log();++ // ── Test 6: Working directory ───────────────────────────────────+ bold("━━━ Test 6: Working directory ━━━\n");++ await sandbox.commands.run("mkdir -p /tmp/workdir/sub");+ await sandbox.files.write("/tmp/workdir/sub/data.txt", "found-it");++ const cwdResult = await sandbox.commands.run("cat data.txt", {+ cwd: "/tmp/workdir/sub",+ });+ check("Working directory respected", cwdResult.stdout.trim() === "found-it");++ const pwdResult = await sandbox.commands.run("pwd", { cwd: "/tmp/workdir" });+ check("pwd reflects cwd", pwdResult.stdout.trim() === "/tmp/workdir");+ console.log();++ // ── Test 7: Shell features ──────────────────────────────────────+ bold("━━━ Test 7: Shell features (pipes, redirects, subshells) ━━━\n");++ // Pipes+ const pipeResult = await sandbox.commands.run("echo 'hello world' | tr ' ' '-'");+ check("Pipe works", pipeResult.stdout.trim() === "hello-world");++ // Subshell+ const subshell = await sandbox.commands.run("echo $(hostname)");+ check("Command substitution works", subshell.stdout.trim().length > 0, subshell.stdout.trim());++ // Redirect+ await sandbox.commands.run("echo redirect-test > /tmp/redirect.txt");+ const redirectContent = await sandbox.files.read("/tmp/redirect.txt");+ check("Redirect to file works", redirectContent.trim() === "redirect-test");++ // Wildcards+ await sandbox.commands.run("touch /tmp/wc-a.txt /tmp/wc-b.txt /tmp/wc-c.txt");+ const wcResult = await sandbox.commands.run("ls /tmp/wc-*.txt | wc -l");+ check("Wildcard expansion works", wcResult.stdout.trim() === "3");++ // Arithmetic+ const arith = await sandbox.commands.run("echo $((42 * 7))");+ check("Arithmetic expansion works", arith.stdout.trim() === "294");++ // Here string (bash-only feature, use bash explicitly)+ const hereStr = await sandbox.commands.run("bash -c \"cat <<< 'here-string-data'\"");+ check("Here string works", hereStr.stdout.trim() === "here-string-data");+ console.log();++ // ── Test 8: Concurrent commands on same sandbox ─────────────────+ bold("━━━ Test 8: Concurrent commands on same sandbox ━━━\n");++ const concurrentStart = Date.now();+ const concurrentPromises = Array.from({ length: 10 }, (_, i) =>+ sandbox!.commands.run(`echo concurrent-${i}`).then((r) => ({+ index: i,+ output: r.stdout.trim(),+ exitCode: r.exitCode,+ })),+ );++ const concurrentResults = await Promise.all(concurrentPromises);+ const concurrentMs = Date.now() - concurrentStart;++ let allCorrect = true;+ for (const r of concurrentResults) {+ if (r.output !== `concurrent-${r.index}` || r.exitCode !== 0) {+ allCorrect = false;+ dim(`Command ${r.index}: expected "concurrent-${r.index}", got "${r.output}" (exit ${r.exitCode})`);+ }+ }+ check("10 concurrent commands all returned correctly", allCorrect);+ dim(`Total concurrent time: ${concurrentMs}ms`);+ console.log();++ // ── Test 9: Command timeout ─────────────────────────────────────+ bold("━━━ Test 9: Command timeout ━━━\n");++ const timeoutStart = Date.now();+ try {+ await sandbox.commands.run("sleep 30", { timeout: 3 });+ // If it returns, check that it was killed (non-zero exit)+ const timeoutMs = Date.now() - timeoutStart;+ check("Command timed out within ~3s", timeoutMs < 10000, `took ${timeoutMs}ms`);+ } catch (err: any) {+ const timeoutMs = Date.now() - timeoutStart;+ check("Command timed out within ~3s", timeoutMs < 10000, `took ${timeoutMs}ms, error: ${err.message}`);+ }+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ if (sandbox) {+ await sandbox.kill();+ green("Sandbox killed");+ }+ }++ // --- 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/examples/test-concurrent.ts b/sdks/typescript/examples/test-concurrent.tsnew file mode 100644index 00000000..c8f0bed1--- /dev/null+++ b/sdks/typescript/examples/test-concurrent.ts@@ -0,0 +1,242 @@+/**+ * Concurrent Sandbox Test+ *+ * Tests:+ * 1. Create 5 sandboxes simultaneously+ * 2. Run commands on all in parallel+ * 3. Verify each sandbox is isolated+ * 4. Kill all in parallel+ *+ * Usage:+ * npx tsx examples/test-concurrent.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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++;+ }+}++const SANDBOX_COUNT = 5;++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Concurrent Sandbox Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ const sandboxes: Sandbox[] = [];++ try {+ // ── Test 1: Create N sandboxes simultaneously ───────────────────+ bold(`━━━ Test 1: Create ${SANDBOX_COUNT} sandboxes simultaneously ━━━\n`);++ const createStart = Date.now();+ const createPromises = Array.from({ length: SANDBOX_COUNT }, (_, i) =>+ Sandbox.create({ template: "base", timeout: 120 })+ .then((sb) => {+ dim(`Sandbox ${i + 1}: ${sb.sandboxId} (${sb.domain})`);+ return sb;+ }),+ );++ const results = await Promise.allSettled(createPromises);+ const createMs = Date.now() - createStart;++ for (let i = 0; i < results.length; i++) {+ const r = results[i];+ if (r.status === "fulfilled") {+ sandboxes.push(r.value);+ check(`Sandbox ${i + 1} created`, true);+ } else {+ check(`Sandbox ${i + 1} created`, false, r.reason.message);+ }+ }+ dim(`Total create time: ${createMs}ms (${(createMs / SANDBOX_COUNT).toFixed(0)}ms avg)`);+ console.log();++ // ── Test 2: Run commands on all in parallel ─────────────────────+ bold("━━━ Test 2: Run commands on all sandboxes in parallel ━━━\n");++ const cmdStart = Date.now();+ const cmdPromises = sandboxes.map((sb, i) =>+ sb.commands.run(`echo "sandbox-${i}-${sb.sandboxId}"`).then((r) => ({+ index: i,+ id: sb.sandboxId,+ result: r,+ })),+ );++ const cmdResults = await Promise.allSettled(cmdPromises);+ const cmdMs = Date.now() - cmdStart;++ for (const r of cmdResults) {+ if (r.status === "fulfilled") {+ const { index, id, result } = r.value;+ const expected = `sandbox-${index}-${id}`;+ check(+ `Sandbox ${index + 1} echo correct`,+ result.stdout.trim() === expected,+ result.stdout.trim(),+ );+ } else {+ check("Command execution", false, r.reason.message);+ }+ }+ dim(`Total command time: ${cmdMs}ms`);+ console.log();++ // ── Test 3: Verify isolation ────────────────────────────────────+ bold("━━━ Test 3: Verify sandbox isolation ━━━\n");++ // Write a unique file to each sandbox+ const writePromises = sandboxes.map((sb, i) =>+ sb.files.write("/tmp/identity.txt", `sandbox-${i}`),+ );+ await Promise.all(writePromises);++ // Read back from each — should only see its own identity+ const readPromises = sandboxes.map((sb, i) =>+ sb.files.read("/tmp/identity.txt").then((content) => ({+ index: i,+ content,+ })),+ );++ const readResults = await Promise.all(readPromises);+ for (const { index, content } of readResults) {+ check(+ `Sandbox ${index + 1} sees only its own data`,+ content === `sandbox-${index}`,+ content,+ );+ }++ // Verify PID namespaces are isolated+ const pidPromises = sandboxes.map((sb, i) =>+ sb.commands.run("echo $$").then((r) => ({+ index: i,+ pid: r.stdout.trim(),+ })),+ );++ const pidResults = await Promise.all(pidPromises);+ // In isolated PID namespaces, PIDs should be low numbers+ for (const { index, pid } of pidResults) {+ dim(`Sandbox ${index + 1} shell PID: ${pid}`);+ }+ // Check that they all have independent PID spaces (PIDs should be same or similar low numbers)+ const uniquePids = new Set(pidResults.map((r) => r.pid));+ // With PID namespaces, most will have the same low PID number+ check(+ "PID namespace isolation (low PIDs)",+ pidResults.every((r) => parseInt(r.pid) < 1000),+ `PIDs: ${pidResults.map((r) => r.pid).join(", ")}`,+ );+ console.log();++ // ── Test 4: Parallel file operations ────────────────────────────+ bold("━━━ Test 4: Parallel file operations across sandboxes ━━━\n");++ // Each sandbox creates 10 files and reads them back+ const fileOpPromises = sandboxes.map(async (sb, i) => {+ const writes = Array.from({ length: 10 }, (_, j) =>+ sb.files.write(`/tmp/file-${j}.txt`, `sb${i}-file${j}`),+ );+ await Promise.all(writes);++ const reads = Array.from({ length: 10 }, (_, j) =>+ sb.files.read(`/tmp/file-${j}.txt`),+ );+ const contents = await Promise.all(reads);++ return {+ index: i,+ allCorrect: contents.every((c, j) => c === `sb${i}-file${j}`),+ count: contents.length,+ };+ });++ const fileResults = await Promise.all(fileOpPromises);+ for (const { index, allCorrect, count } of fileResults) {+ check(+ `Sandbox ${index + 1}: ${count} files written and verified`,+ allCorrect,+ );+ }+ console.log();++ // ── Test 5: List all sandboxes (API check) ──────────────────────+ bold("━━━ Test 5: Verify all sandboxes visible via API ━━━\n");++ // Use isRunning to verify all are still up+ const statusPromises = sandboxes.map((sb, i) =>+ sb.isRunning().then((running) => ({ index: i, running })),+ );+ const statuses = await Promise.all(statusPromises);+ for (const { index, running } of statuses) {+ check(`Sandbox ${index + 1} still running`, running);+ }+ console.log();++ // ── Test 6: Kill all in parallel ────────────────────────────────+ bold(`━━━ Test 6: Kill all ${SANDBOX_COUNT} sandboxes simultaneously ━━━\n`);++ const killStart = Date.now();+ const killPromises = sandboxes.map((sb, i) =>+ sb.kill().then(() => ({ index: i, success: true }))+ .catch((err) => ({ index: i, success: false, error: err.message })),+ );++ const killResults = await Promise.all(killPromises);+ const killMs = Date.now() - killStart;++ for (const r of killResults) {+ check(`Sandbox ${r.index + 1} killed`, r.success, (r as any).error);+ }+ dim(`Total kill time: ${killMs}ms`);++ // Verify they're all gone+ await new Promise((r) => globalThis.setTimeout(r, 1000));+ const postKillPromises = sandboxes.map((sb, i) =>+ sb.isRunning().then((running) => ({ index: i, running })),+ );+ const postKill = await Promise.all(postKillPromises);+ for (const { index, running } of postKill) {+ check(`Sandbox ${index + 1} confirmed stopped`, !running);+ }+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ failed++;+ // Kill any sandboxes that were created+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch {}+ }+ }++ // --- 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/examples/test-domain-tls.ts b/sdks/typescript/examples/test-domain-tls.tsnew file mode 100644index 00000000..0c0dd0ba--- /dev/null+++ b/sdks/typescript/examples/test-domain-tls.ts@@ -0,0 +1,235 @@+/**+ * Domain & TLS Verification Test+ *+ * Tests:+ * 1. Each sandbox gets a unique subdomain+ * 2. HTTPS works with valid Let's Encrypt cert+ * 3. HTTP server inside sandbox is reachable via subdomain+ * 4. Multiple subdomains get individual certs+ * 5. Subdomain routes to correct sandbox+ *+ * Usage:+ * npx tsx examples/test-domain-tls.ts+ */++import { Sandbox } from "../src/index";+import * as tls from "tls";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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`); }++function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++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++;+ }+}++function getTlsCertInfo(hostname: string): Promise<{ issuer: string; subject: string; validTo: string; valid: boolean }> {+ return new Promise((resolve, reject) => {+ const socket = tls.connect(443, hostname, { servername: hostname }, () => {+ const cert = socket.getPeerCertificate();+ const authorized = socket.authorized;+ socket.end();+ resolve({+ issuer: cert.issuer?.O || "unknown",+ subject: cert.subject?.CN || "unknown",+ validTo: cert.valid_to || "unknown",+ valid: authorized,+ });+ });+ socket.on("error", reject);+ socket.setTimeout(10000, () => {+ socket.destroy();+ reject(new Error("TLS connection timeout"));+ });+ });+}++// Simple HTTP server for sandbox+const HTTP_SERVER = `+const http = require('http');+const os = require('os');+const server = http.createServer((req, res) => {+ res.writeHead(200, {'Content-Type':'application/json'});+ res.end(JSON.stringify({+ path: req.url,+ hostname: os.hostname(),+ sandboxId: process.env.SANDBOX_ID || 'unknown',+ timestamp: Date.now()+ }));+});+server.listen(80, '0.0.0.0', () => console.log('Server ready'));+`;++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Domain & TLS Verification Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ const sandboxes: Sandbox[] = [];++ try {+ // ── Test 1: Unique subdomains ───────────────────────────────────+ bold("━━━ Test 1: Unique subdomain assignment ━━━\n");++ // Create 3 sandboxes and verify unique domains+ for (let i = 0; i < 3; i++) {+ const sb = await Sandbox.create({ template: "node", timeout: 120 });+ sandboxes.push(sb);+ dim(`Sandbox ${i + 1}: ${sb.sandboxId} → ${sb.domain}`);+ }++ const domains = sandboxes.map(s => s.domain);+ const uniqueDomains = new Set(domains);+ check("All 3 sandboxes got unique domains", uniqueDomains.size === 3);+ check("All domains end with .workers.opensandbox.ai",+ domains.every(d => d.endsWith(".workers.opensandbox.ai")));+ check("All domains are subdomains (single level)",+ domains.every(d => d.split(".workers.opensandbox.ai")[0].indexOf(".") === -1));+ console.log();++ // ── Test 2: TLS certificate validation ──────────────────────────+ bold("━━━ Test 2: TLS certificate validation ━━━\n");++ // Start HTTP servers on all sandboxes+ for (let i = 0; i < sandboxes.length; i++) {+ await sandboxes[i].files.write("/tmp/server.js", HTTP_SERVER);+ await sandboxes[i].commands.run(+ `SANDBOX_ID=${sandboxes[i].sandboxId} nohup node /tmp/server.js > /tmp/server.log 2>&1 &`,+ );+ }+ await sleep(2000);++ // Check TLS cert on first sandbox+ try {+ const certInfo = await getTlsCertInfo(sandboxes[0].domain);+ check("TLS certificate is valid", certInfo.valid);+ check("Certificate issued by Let's Encrypt or similar",+ certInfo.issuer.includes("Let's Encrypt") ||+ certInfo.issuer.includes("R3") ||+ certInfo.issuer.includes("R10") ||+ certInfo.issuer.includes("R11") ||+ certInfo.issuer.includes("E5") ||+ certInfo.issuer.includes("E6"),+ certInfo.issuer);+ dim(`Issuer: ${certInfo.issuer}`);+ dim(`Subject: ${certInfo.subject}`);+ dim(`Valid to: ${certInfo.validTo}`);+ } catch (err: any) {+ check("TLS connection succeeded", false, err.message);+ }+ console.log();++ // ── Test 3: HTTPS requests work ─────────────────────────────────+ bold("━━━ Test 3: HTTPS requests to sandbox servers ━━━\n");++ for (let i = 0; i < sandboxes.length; i++) {+ try {+ const resp = await fetch(`https://${sandboxes[i].domain}/test-path`);+ check(`Sandbox ${i + 1}: HTTPS 200`, resp.ok, `status ${resp.status}`);++ if (resp.ok) {+ const data = await resp.json();+ check(`Sandbox ${i + 1}: correct path`, data.path === "/test-path", data.path);+ check(`Sandbox ${i + 1}: has hostname`, !!data.hostname);+ }+ } catch (err: any) {+ check(`Sandbox ${i + 1}: HTTPS request`, false, err.message);+ }+ }+ console.log();++ // ── Test 4: Subdomain routes to correct sandbox ─────────────────+ bold("━━━ Test 4: Subdomain routing isolation ━━━\n");++ // Each sandbox server returns its sandbox ID — verify routing is correct+ const routingResults = await Promise.all(+ sandboxes.map(async (sb, i) => {+ try {+ const resp = await fetch(`https://${sb.domain}/`);+ const data = await resp.json();+ return { index: i, sandboxId: sb.sandboxId, returnedId: data.sandboxId, hostname: data.hostname };+ } catch (err: any) {+ return { index: i, sandboxId: sb.sandboxId, returnedId: "error", hostname: err.message };+ }+ }),+ );++ for (const r of routingResults) {+ check(+ `Sandbox ${r.index + 1}: routed to correct container`,+ r.returnedId === r.sandboxId,+ `expected ${r.sandboxId}, got ${r.returnedId}`,+ );+ }++ // Cross-check: request to sandbox 1's domain should NOT get sandbox 2's response+ if (sandboxes.length >= 2) {+ const cross1 = await fetch(`https://${sandboxes[0].domain}/`);+ const cross1Data = await cross1.json();+ const cross2 = await fetch(`https://${sandboxes[1].domain}/`);+ const cross2Data = await cross2.json();+ check(+ "Cross-routing: different sandboxes return different IDs",+ cross1Data.sandboxId !== cross2Data.sandboxId,+ );+ }+ console.log();++ // ── Test 5: Multiple methods ────────────────────────────────────+ bold("━━━ Test 5: HTTP methods through TLS ━━━\n");++ const domain = sandboxes[0].domain;+ const getResp = await fetch(`https://${domain}/get-test`);+ check("GET request works", getResp.ok);++ const postResp = await fetch(`https://${domain}/post-test`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ test: true }),+ });+ check("POST request works", postResp.ok);++ const putResp = await fetch(`https://${domain}/put-test`, {+ method: "PUT",+ body: "put-data",+ });+ check("PUT request works", putResp.ok);+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ // Kill all sandboxes+ for (const sb of sandboxes) {+ try { await sb.kill(); } catch {}+ }+ if (sandboxes.length > 0) green(`${sandboxes.length} sandboxes killed`);+ }++ // --- 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/examples/test-file-ops.ts b/sdks/typescript/examples/test-file-ops.tsnew file mode 100644index 00000000..c4f49f8f--- /dev/null+++ b/sdks/typescript/examples/test-file-ops.ts@@ -0,0 +1,205 @@+/**+ * File Operations Edge Cases Test+ *+ * Tests:+ * 1. Large file write/read (1MB)+ * 2. Binary-like content handling+ * 3. Deeply nested directories+ * 4. File deletion and overwrite+ * 5. List large directories+ * 6. Special characters in content+ * 7. Empty file handling+ * 8. File exists / not exists+ *+ * Usage:+ * npx tsx examples/test-file-ops.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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("║ File Operations Edge Cases Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ let sandbox: Sandbox | null = null;++ try {+ sandbox = await Sandbox.create({ template: "base", timeout: 120 });+ green(`Created sandbox: ${sandbox.sandboxId}`);+ console.log();++ // ── Test 1: Large file ──────────────────────────────────────────+ bold("━━━ Test 1: Large file (1MB) ━━━\n");++ const oneMB = "X".repeat(1024 * 1024);+ const writeStart = Date.now();+ await sandbox.files.write("/tmp/large.txt", oneMB);+ const writeMs = Date.now() - writeStart;+ dim(`Write: ${writeMs}ms`);++ const readStart = Date.now();+ const largeContent = await sandbox.files.read("/tmp/large.txt");+ const readMs = Date.now() - readStart;+ dim(`Read: ${readMs}ms`);++ check("1MB file size preserved", largeContent.length === oneMB.length, `${largeContent.length} bytes`);+ check("1MB file content intact", largeContent === oneMB);+ console.log();++ // ── Test 2: Special characters in content ───────────────────────+ bold("━━━ Test 2: Special characters ━━━\n");++ const specialContent = 'Hello "world" & <tag> \'quotes\' \\ newline\nTab\there 日本語 emoji🎉 nullish ?? chain?.';+ await sandbox.files.write("/tmp/special.txt", specialContent);+ const specialRead = await sandbox.files.read("/tmp/special.txt");+ check("Special characters preserved", specialRead === specialContent, `got: ${specialRead.substring(0, 50)}...`);++ // JSON content+ const jsonContent = JSON.stringify({ key: "value", nested: { arr: [1, 2, 3] }, unicode: "日本語" }, null, 2);+ await sandbox.files.write("/tmp/data.json", jsonContent);+ const jsonRead = await sandbox.files.read("/tmp/data.json");+ check("JSON content preserved", jsonRead === jsonContent);++ // Multi-line content+ const multiline = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}: Some content here`).join("\n");+ await sandbox.files.write("/tmp/multiline.txt", multiline);+ const multiRead = await sandbox.files.read("/tmp/multiline.txt");+ check("100-line file preserved", multiRead === multiline, `lines: ${multiRead.split("\n").length}`);+ console.log();++ // ── Test 3: Deeply nested directories ───────────────────────────+ bold("━━━ Test 3: Deeply nested directories ━━━\n");++ const deepPath = "/tmp/a/b/c/d/e/f/g/h";+ // Create nested dirs step by step using commands (SDK mkdir doesn't do recursive)+ await sandbox.commands.run(`mkdir -p ${deepPath}`);+ await sandbox.files.write(`${deepPath}/deep.txt`, "bottom-of-tree");+ const deepContent = await sandbox.files.read(`${deepPath}/deep.txt`);+ check("8-level nested file created and read", deepContent === "bottom-of-tree");++ // List intermediate directory+ const midEntries = await sandbox.files.list("/tmp/a/b/c/d");+ check("Intermediate dir lists correctly", midEntries.some(e => e.name === "e" && e.isDir));+ console.log();++ // ── Test 4: File deletion and overwrite ──────────────────────────+ bold("━━━ Test 4: File deletion and overwrite ━━━\n");++ // Write → overwrite → verify new content+ await sandbox.files.write("/tmp/overwrite.txt", "original");+ let content = await sandbox.files.read("/tmp/overwrite.txt");+ check("Original content written", content === "original");++ await sandbox.files.write("/tmp/overwrite.txt", "overwritten");+ content = await sandbox.files.read("/tmp/overwrite.txt");+ check("Overwritten content correct", content === "overwritten");++ // Overwrite with shorter content+ await sandbox.files.write("/tmp/overwrite.txt", "short");+ content = await sandbox.files.read("/tmp/overwrite.txt");+ check("Shorter overwrite correct (no trailing data)", content === "short");++ // Delete+ const existsBefore = await sandbox.files.exists("/tmp/overwrite.txt");+ check("File exists before delete", existsBefore);++ await sandbox.files.remove("/tmp/overwrite.txt");+ const existsAfter = await sandbox.files.exists("/tmp/overwrite.txt");+ check("File gone after delete", !existsAfter);++ // Delete directory+ await sandbox.files.remove("/tmp/a");+ const dirGone = await sandbox.files.exists(`${deepPath}/deep.txt`);+ check("Recursive directory deletion", !dirGone);+ console.log();++ // ── Test 5: Large directory listing ─────────────────────────────+ bold("━━━ Test 5: Large directory listing ━━━\n");++ // Create 50 files+ await sandbox.commands.run(+ "for i in $(seq 1 50); do echo content-$i > /tmp/listtest-$i.txt; done",+ );+ const entries = await sandbox.files.list("/tmp");+ const listTestFiles = entries.filter(e => e.name.startsWith("listtest-"));+ check("50 files visible in listing", listTestFiles.length === 50, `found ${listTestFiles.length}`);++ // Verify entries have correct metadata+ const entry = listTestFiles[0];+ check("Entry has name", !!entry.name);+ check("Entry has isDir=false", entry.isDir === false);+ check("Entry has size > 0", entry.size > 0, `size=${entry.size}`);+ console.log();++ // ── Test 6: Empty file ──────────────────────────────────────────+ bold("━━━ Test 6: Empty file handling ━━━\n");++ await sandbox.files.write("/tmp/empty.txt", "");+ const emptyContent = await sandbox.files.read("/tmp/empty.txt");+ check("Empty file returns empty string", emptyContent === "", `got: "${emptyContent}"`);+ check("Empty file exists", await sandbox.files.exists("/tmp/empty.txt"));+ console.log();++ // ── Test 7: File exists / not exists ────────────────────────────+ bold("━━━ Test 7: File exists checks ━━━\n");++ check("Existing file → true", await sandbox.files.exists("/tmp/special.txt"));+ check("Non-existent file → false", !(await sandbox.files.exists("/tmp/nope-no-way.txt")));+ check("Non-existent deep path → false", !(await sandbox.files.exists("/tmp/no/such/path/file.txt")));+ console.log();++ // ── Test 8: Binary-like content ─────────────────────────────────+ bold("━━━ Test 8: Write via commands + read via SDK ━━━\n");++ // Write a script, execute it, read output via SDK+ await sandbox.commands.run('dd if=/dev/urandom bs=256 count=1 2>/dev/null | base64 > /tmp/random.b64');+ const b64Content = await sandbox.files.read("/tmp/random.b64");+ check("Base64 random data readable", b64Content.length > 100, `${b64Content.length} chars`);++ // Write via command, read via SDK+ await sandbox.commands.run('echo -n "command-written" > /tmp/cmd-file.txt');+ const cmdFileContent = await sandbox.files.read("/tmp/cmd-file.txt");+ check("Command-written file readable via SDK", cmdFileContent === "command-written");+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ if (sandbox) {+ await sandbox.kill();+ green("Sandbox killed");+ }+ }++ // --- 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/examples/test-hibernation-stress.ts b/sdks/typescript/examples/test-hibernation-stress.tsnew file mode 100644index 00000000..fdbb21d4--- /dev/null+++ b/sdks/typescript/examples/test-hibernation-stress.ts@@ -0,0 +1,259 @@+/**+ * Hibernation Stress Test+ *+ * Tests:+ * 1. Multiple hibernate/wake cycles on same sandbox+ * 2. Large state persistence across hibernation+ * 3. Rapid auto-wake via HTTP after hibernation+ * 4. Process state survives across cycles+ *+ * Usage:+ * npx tsx examples/test-hibernation-stress.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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`); }+function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }++function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++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("║ Hibernation Stress Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ let sandbox: Sandbox | null = null;++ try {+ // ── Setup: Create sandbox with a persistent server ──────────────+ bold("━━━ Setup: Create sandbox with counter server ━━━\n");++ sandbox = await Sandbox.create({ template: "node", timeout: 300 });+ green(`Created: ${sandbox.sandboxId}`);+ dim(`Domain: ${sandbox.domain}`);++ // Write a server that maintains an in-memory counter+ const SERVER_CODE = `+const http = require('http');+const fs = require('fs');+let counter = 0;+try { counter = parseInt(fs.readFileSync('/tmp/counter.txt', 'utf8')) || 0; } catch {}+const server = http.createServer((req, res) => {+ if (req.url === '/increment') {+ counter++;+ fs.writeFileSync('/tmp/counter.txt', String(counter));+ res.writeHead(200, {'Content-Type':'application/json'});+ res.end(JSON.stringify({counter}));+ } else if (req.url === '/health') {+ res.writeHead(200, {'Content-Type':'application/json'});+ res.end(JSON.stringify({counter, uptime: process.uptime().toFixed(1)+'s'}));+ } else {+ res.writeHead(404); res.end('not found');+ }+});+server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));+`;++ await sandbox.files.write("/tmp/counter-server.js", SERVER_CODE);+ await sandbox.commands.run("nohup node /tmp/counter-server.js > /tmp/server.log 2>&1 &");+ await sleep(1500);++ // Verify server is up+ const healthResp = await fetch(`https://${sandbox.domain}/health`);+ check("Counter server started", healthResp.ok);+ const health = await healthResp.json();+ dim(`Initial state: counter=${health.counter}, uptime=${health.uptime}`);+ console.log();++ // ── Test 1: Multiple hibernate/wake cycles ──────────────────────+ bold("━━━ Test 1: Multiple hibernate/wake cycles (3x) ━━━\n");+ const cycleTimes: { hibernate: number; wake: number }[] = [];++ for (let cycle = 1; cycle <= 3; cycle++) {+ cyan(`Cycle ${cycle}/3: Incrementing counter...`);++ // Increment counter before hibernate+ const incResp = await fetch(`https://${sandbox.domain}/increment`);+ const incData = await incResp.json();+ dim(`Counter = ${incData.counter}`);++ // Hibernate+ cyan(`Cycle ${cycle}/3: Hibernating...`);+ const hibStart = Date.now();+ await sandbox.hibernate();+ const hibMs = Date.now() - hibStart;++ await sleep(1000);++ // Wake+ cyan(`Cycle ${cycle}/3: Waking...`);+ const wakeStart = Date.now();+ await sandbox.wake();+ const wakeMs = Date.now() - wakeStart;++ // Need to wait a moment for server to be ready after restore+ await sleep(2000);++ cycleTimes.push({ hibernate: hibMs, wake: wakeMs });+ dim(`Hibernate: ${hibMs}ms, Wake: ${wakeMs}ms`);++ // Verify counter persisted+ const postWakeResp = await fetch(`https://${sandbox.domain}/health`);+ if (postWakeResp.ok) {+ const postWake = await postWakeResp.json();+ check(`Cycle ${cycle}: Counter persisted (${postWake.counter})`, postWake.counter === cycle);+ } else {+ check(`Cycle ${cycle}: Server responded after wake`, false, `status ${postWakeResp.status}`);+ }+ }++ console.log();+ dim("Cycle timing summary:");+ cycleTimes.forEach((t, i) => dim(` Cycle ${i + 1}: hibernate=${t.hibernate}ms, wake=${t.wake}ms`));+ console.log();++ // ── Test 2: Large state persistence ─────────────────────────────+ bold("━━━ Test 2: Large state persistence across hibernation ━━━\n");++ // Write a 500KB file+ const largeData = "A".repeat(500 * 1024);+ cyan("Writing 500KB file...");+ await sandbox.files.write("/tmp/large-state.bin", largeData);++ // Write 100 small files+ cyan("Writing 100 small files...");+ await sandbox.commands.run(+ "for i in $(seq 1 100); do echo \"file-content-$i\" > /tmp/batch-$i.txt; done",+ );++ // Hibernate with all this state+ cyan("Hibernating with large state...");+ const bigHibStart = Date.now();+ await sandbox.hibernate();+ const bigHibMs = Date.now() - bigHibStart;+ dim(`Hibernate with large state: ${bigHibMs}ms`);++ await sleep(1000);++ // Wake+ cyan("Waking...");+ const bigWakeStart = Date.now();+ await sandbox.wake();+ const bigWakeMs = Date.now() - bigWakeStart;+ dim(`Wake with large state: ${bigWakeMs}ms`);+ await sleep(1500);++ // Verify large file+ const largeContent = await sandbox.files.read("/tmp/large-state.bin");+ check("500KB file persisted", largeContent.length === largeData.length, `got ${largeContent.length} bytes`);+ check("500KB file content intact", largeContent === largeData);++ // Verify batch files (spot check)+ const file1 = await sandbox.files.read("/tmp/batch-1.txt");+ check("Batch file 1 persisted", file1.trim() === "file-content-1", file1.trim());+ const file50 = await sandbox.files.read("/tmp/batch-50.txt");+ check("Batch file 50 persisted", file50.trim() === "file-content-50", file50.trim());+ const file100 = await sandbox.files.read("/tmp/batch-100.txt");+ check("Batch file 100 persisted", file100.trim() === "file-content-100", file100.trim());+ console.log();++ // ── Test 3: Rapid auto-wake ─────────────────────────────────────+ bold("━━━ Test 3: Rapid auto-wake via HTTP ━━━\n");++ // Hibernate+ cyan("Hibernating for auto-wake test...");+ await sandbox.hibernate();+ await sleep(1000);++ // Immediately hit the domain - should trigger auto-wake+ cyan("Sending HTTP request to sleeping sandbox...");+ const autoWakeStart = Date.now();+ const autoWakeResp = await fetch(`https://${sandbox.domain}/health`);+ const autoWakeMs = Date.now() - autoWakeStart;++ check("Auto-wake HTTP returned 200", autoWakeResp.ok, `status ${autoWakeResp.status}`);+ if (autoWakeResp.ok) {+ const autoWakeData = await autoWakeResp.json();+ check("Counter still intact after auto-wake", autoWakeData.counter === 3, `counter=${autoWakeData.counter}`);+ dim(`Auto-wake latency: ${autoWakeMs}ms`);+ }+ console.log();++ // ── Test 4: Process state survives ──────────────────────────────+ bold("━━━ Test 4: Process state survives hibernation ━━━\n");++ // Update sandbox reference after auto-wake restored it+ sandbox = await Sandbox.connect(sandbox.sandboxId);++ // Get PID of node server before hibernate+ const pidBefore = await sandbox.commands.run("cat /tmp/server.log | head -1");+ dim(`Server log: ${pidBefore.stdout.trim()}`);++ // Increment counter to 4+ await fetch(`https://${sandbox.domain}/increment`);+ const preHibHealth = await fetch(`https://${sandbox.domain}/health`);+ const preHibData = await preHibHealth.json();+ check("Counter at 4 before final hibernate", preHibData.counter === 4, `counter=${preHibData.counter}`);++ // One more hibernate/wake cycle (use auto-wake via HTTP to avoid restore conflict)+ await sandbox.hibernate();+ await sleep(1000);++ // Auto-wake by hitting the domain instead of explicit wake()+ const finalHealth = await fetch(`https://${sandbox.domain}/health`);+ if (finalHealth.ok) {+ const finalData = await finalHealth.json();+ check("Counter persisted through final cycle", finalData.counter === 4, `counter=${finalData.counter}`);+ green(`Final state: counter=${finalData.counter}, uptime=${finalData.uptime}`);+ } else {+ check("Final health check", false, `status ${finalHealth.status}`);+ }+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ if (sandbox) {+ try {+ // Re-connect in case wake changed state+ const s = await Sandbox.connect(sandbox.sandboxId);+ await s.kill();+ green("Sandbox killed");+ } catch {+ dim("Sandbox may have already been cleaned up");+ }+ }+ }++ // --- 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/examples/test-multi-template.ts b/sdks/typescript/examples/test-multi-template.tsnew file mode 100644index 00000000..01a4b36c--- /dev/null+++ b/sdks/typescript/examples/test-multi-template.ts@@ -0,0 +1,154 @@+/**+ * Multi-Template Production Test+ *+ * Verifies all 3 templates (base, python, node) create, run commands,+ * and have the expected runtimes available.+ *+ * Usage:+ * npx tsx examples/test-multi-template.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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++;+ }+}++interface TemplateTest {+ template: string;+ expectedBinary: string;+ versionCmd: string;+ versionPrefix: string;+ testCmd: string;+ testExpected: string;+}++const TEMPLATES: TemplateTest[] = [+ {+ template: "base",+ expectedBinary: "bash",+ versionCmd: "bash --version | head -1",+ versionPrefix: "GNU bash",+ testCmd: "echo 'hello from base'",+ testExpected: "hello from base",+ },+ {+ template: "python",+ expectedBinary: "python3",+ versionCmd: "python3 --version",+ versionPrefix: "Python 3",+ testCmd: "python3 -c \"print(2 + 2)\"",+ testExpected: "4",+ },+ {+ template: "node",+ expectedBinary: "node",+ versionCmd: "node --version",+ versionPrefix: "v",+ testCmd: "node -e \"console.log(JSON.stringify({ok:true}))\"",+ testExpected: '{"ok":true}',+ },+];++async function testTemplate(t: TemplateTest, index: number): Promise<{ passed: number; failed: number }> {+ let p = 0;+ let f = 0;++ const localCheck = (desc: string, condition: boolean, detail?: string) => {+ if (condition) { green(desc); p++; } else { red(`${desc}${detail ? ` (${detail})` : ""}`); f++; }+ };++ bold(`\n━━━ Template ${index + 1}/3: "${t.template}" ━━━\n`);+ let sandbox: Sandbox | null = null;++ try {+ // Create+ const start = Date.now();+ sandbox = await Sandbox.create({ template: t.template, timeout: 120 });+ const createMs = Date.now() - start;+ localCheck(`Created ${t.template} sandbox (${createMs}ms)`, true);+ dim(`ID: ${sandbox.sandboxId}`);+ dim(`Domain: ${sandbox.domain}`);++ // Verify domain assigned+ localCheck(`Domain assigned`, !!sandbox.domain);++ // Check expected binary exists+ const which = await sandbox.commands.run(`which ${t.expectedBinary}`);+ localCheck(`${t.expectedBinary} binary exists`, which.exitCode === 0, which.stderr.trim());++ // Get version+ const version = await sandbox.commands.run(t.versionCmd);+ localCheck(+ `Version starts with "${t.versionPrefix}"`,+ version.stdout.trim().startsWith(t.versionPrefix),+ version.stdout.trim(),+ );+ dim(`Version: ${version.stdout.trim()}`);++ // Run template-specific test command+ const test = await sandbox.commands.run(t.testCmd);+ localCheck(+ `Test command output correct`,+ test.stdout.trim() === t.testExpected,+ `expected "${t.testExpected}", got "${test.stdout.trim()}"`,+ );++ // Verify basic file ops work+ await sandbox.files.write("/tmp/template-test.txt", `from-${t.template}`);+ const content = await sandbox.files.read("/tmp/template-test.txt");+ localCheck(`File ops work`, content === `from-${t.template}`);++ // Verify uname (should always be Linux)+ const uname = await sandbox.commands.run("uname -s");+ localCheck(`Running on Linux`, uname.stdout.trim() === "Linux");++ } catch (err: any) {+ red(` Error testing ${t.template}: ${err.message}`);+ f++;+ } finally {+ if (sandbox) {+ await sandbox.kill();+ dim(`Sandbox killed`);+ }+ }++ return { passed: p, failed: f };+}++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Multi-Template Production Test ║");+ bold("╚══════════════════════════════════════════════════╝");++ for (let i = 0; i < TEMPLATES.length; i++) {+ const result = await testTemplate(TEMPLATES[i], i);+ passed += result.passed;+ failed += result.failed;+ }++ console.log();+ 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/examples/test-python-sdk.ts b/sdks/typescript/examples/test-python-sdk.tsnew file mode 100644index 00000000..d1adb4d3--- /dev/null+++ b/sdks/typescript/examples/test-python-sdk.ts@@ -0,0 +1,151 @@+/**+ * Python SDK Production Test+ *+ * Validates the Python SDK works end-to-end against production by running+ * the Python test script inside a sandbox (meta: using TS SDK to test Python SDK).+ *+ * Usage:+ * npx tsx examples/test-python-sdk.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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++;+ }+}++// Python test script that exercises all SDK operations and prints JSON results+const PYTHON_TEST_SCRIPT = `+import json+import os++results = {}++# Test 1: Basic echo+import subprocess+r = subprocess.run(["echo", "hello-from-python"], capture_output=True, text=True)+results["echo"] = r.stdout.strip()++# Test 2: File write + read+with open("/tmp/py-test.txt", "w") as f:+ f.write("python-sdk-data")+with open("/tmp/py-test.txt", "r") as f:+ results["file_content"] = f.read()++# Test 3: Environment variables+results["home"] = os.environ.get("HOME", "unknown")+results["path_exists"] = "PATH" in os.environ++# Test 4: Nested directory+os.makedirs("/tmp/py-nested/deep/dir", exist_ok=True)+with open("/tmp/py-nested/deep/dir/file.txt", "w") as f:+ f.write("nested-content")+with open("/tmp/py-nested/deep/dir/file.txt", "r") as f:+ results["nested"] = f.read()++# Test 5: Python-specific features+import sys+results["python_version"] = sys.version.split()[0]+results["platform"] = sys.platform++# Test 6: Math/stdlib+import math+results["pi"] = str(round(math.pi, 5))++# Test 7: JSON handling+data = {"key": "value", "number": 42, "nested": {"a": True}}+results["json_roundtrip"] = json.loads(json.dumps(data)) == data++print(json.dumps(results))+`;++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Python SDK Production Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ let sandbox: Sandbox | null = null;++ try {+ // --- Create sandbox with Python template ---+ bold("[1/4] Creating Python sandbox...");+ sandbox = await Sandbox.create({+ template: "python",+ timeout: 120,+ });+ green(`Created: ${sandbox.sandboxId}`);+ dim(`Domain: ${sandbox.domain}`);+ console.log();++ // --- Write and run Python test script ---+ bold("[2/4] Writing Python test script...");+ await sandbox.files.write("/tmp/test_sdk.py", PYTHON_TEST_SCRIPT);+ green("Script written to /tmp/test_sdk.py");+ console.log();++ bold("[3/4] Running Python tests inside sandbox...");+ const result = await sandbox.commands.run("python3 /tmp/test_sdk.py", { timeout: 30 });+ check("Python script exited cleanly", result.exitCode === 0, `exit code: ${result.exitCode}`);++ if (result.exitCode !== 0) {+ dim(`stderr: ${result.stderr}`);+ dim(`stdout: ${result.stdout}`);+ } else {+ const data = JSON.parse(result.stdout.trim());+ check("Echo command works", data.echo === "hello-from-python", data.echo);+ check("File write/read works", data.file_content === "python-sdk-data", data.file_content);+ check("HOME env var present", data.home !== "unknown", data.home);+ check("PATH env var exists", data.path_exists === true);+ check("Nested directory file works", data.nested === "nested-content", data.nested);+ check("Python version detected", data.python_version.startsWith("3."), data.python_version);+ check("Platform is Linux", data.platform === "linux", data.platform);+ check("Math.pi correct", data.pi === "3.14159", data.pi);+ check("JSON roundtrip works", data.json_roundtrip === true);+ dim(`Python ${data.python_version} on ${data.platform}`);+ }+ console.log();++ // --- Verify file ops from SDK side ---+ bold("[4/4] Verifying files from TypeScript SDK...");+ const content = await sandbox.files.read("/tmp/py-test.txt");+ check("TS SDK can read Python-written file", content === "python-sdk-data", content);++ const entries = await sandbox.files.list("/tmp/py-nested/deep/dir");+ check("TS SDK can list Python-created directory", entries.some(e => e.name === "file.txt"));+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ failed++;+ } finally {+ if (sandbox) {+ await sandbox.kill();+ green("Sandbox killed");+ }+ }++ // --- 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/examples/test-reconnect.ts b/sdks/typescript/examples/test-reconnect.tsnew file mode 100644index 00000000..e8cbb719--- /dev/null+++ b/sdks/typescript/examples/test-reconnect.ts@@ -0,0 +1,185 @@+/**+ * SDK Connect/Reconnect Test+ *+ * Tests:+ * 1. Create sandbox, disconnect, reconnect via Sandbox.connect()+ * 2. Verify state persists across connections+ * 3. Multiple connect() calls to same sandbox+ * 4. Operations work on reconnected instance+ *+ * Usage:+ * npx tsx examples/test-reconnect.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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("║ SDK Connect/Reconnect Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ let sandboxId = "";++ try {+ // ── Test 1: Create and store ID ─────────────────────────────────+ bold("━━━ Test 1: Create sandbox and store ID ━━━\n");++ const original = await Sandbox.create({ template: "base", timeout: 120 });+ sandboxId = original.sandboxId;+ green(`Created: ${sandboxId}`);+ dim(`Domain: ${original.domain}`);++ // Write state+ await original.files.write("/tmp/reconnect-test.txt", "original-data");+ await original.commands.run("echo 'state-marker' > /tmp/marker.txt");+ green("State written to sandbox");+ console.log();++ // ── Test 2: Reconnect via Sandbox.connect() ─────────────────────+ bold("━━━ Test 2: Reconnect via Sandbox.connect() ━━━\n");++ const reconnected = await Sandbox.connect(sandboxId);+ check("Reconnect succeeded", !!reconnected);+ check("Same sandbox ID", reconnected.sandboxId === sandboxId);+ check("Domain matches", reconnected.domain === original.domain, reconnected.domain);+ check("Status is running", reconnected.status === "running", reconnected.status);+ console.log();++ // ── Test 3: Read state from reconnected instance ────────────────+ bold("━━━ Test 3: State persists across connections ━━━\n");++ const fileContent = await reconnected.files.read("/tmp/reconnect-test.txt");+ check("File from original instance readable", fileContent === "original-data", fileContent);++ const markerContent = await reconnected.files.read("/tmp/marker.txt");+ check("Command output file persisted", markerContent.trim() === "state-marker");++ // Write new data from reconnected instance+ await reconnected.files.write("/tmp/reconnect-new.txt", "from-reconnected");+ const newContent = await reconnected.files.read("/tmp/reconnect-new.txt");+ check("Write from reconnected instance works", newContent === "from-reconnected");+ console.log();++ // ── Test 4: Commands work on reconnected instance ───────────────+ bold("━━━ Test 4: Commands work on reconnected instance ━━━\n");++ const echo = await reconnected.commands.run("echo reconnected-echo");+ check("Echo command works", echo.stdout.trim() === "reconnected-echo");+ check("Exit code is 0", echo.exitCode === 0);++ const uname = await reconnected.commands.run("uname -s");+ check("Uname returns Linux", uname.stdout.trim() === "Linux");++ // Env vars+ const envResult = await reconnected.commands.run("echo $TEST_VAR", {+ env: { TEST_VAR: "reconnected-env" },+ });+ check("Env vars work on reconnected instance", envResult.stdout.trim() === "reconnected-env");++ // File list+ const entries = await reconnected.files.list("/tmp");+ check("File listing works", entries.some(e => e.name === "reconnect-test.txt"));+ check("New file visible in listing", entries.some(e => e.name === "reconnect-new.txt"));+ console.log();++ // ── Test 5: Multiple simultaneous connections ───────────────────+ bold("━━━ Test 5: Multiple simultaneous connections ━━━\n");++ const conn1 = await Sandbox.connect(sandboxId);+ const conn2 = await Sandbox.connect(sandboxId);+ const conn3 = await Sandbox.connect(sandboxId);++ check("3 connections to same sandbox succeeded", !!conn1 && !!conn2 && !!conn3);++ // All should be able to read+ const [read1, read2, read3] = await Promise.all([+ conn1.files.read("/tmp/reconnect-test.txt"),+ conn2.files.read("/tmp/reconnect-test.txt"),+ conn3.files.read("/tmp/reconnect-test.txt"),+ ]);++ check("All connections read same data",+ read1 === "original-data" && read2 === "original-data" && read3 === "original-data");++ // Write from conn1, read from conn2+ await conn1.files.write("/tmp/cross-conn.txt", "from-conn1");+ const crossRead = await conn2.files.read("/tmp/cross-conn.txt");+ check("Write from conn1 visible to conn2", crossRead === "from-conn1");+ console.log();++ // ── Test 6: isRunning on reconnected instance ───────────────────+ bold("━━━ Test 6: isRunning on reconnected instance ━━━\n");++ const running = await reconnected.isRunning();+ check("isRunning returns true", running);+ console.log();++ // ── Test 7: Kill from reconnected instance ──────────────────────+ bold("━━━ Test 7: Kill from reconnected instance ━━━\n");++ await reconnected.kill();+ green("Killed from reconnected instance");++ await new Promise(r => globalThis.setTimeout(r, 500));++ // Verify from original reference+ const stillRunning = await original.isRunning();+ check("Original ref sees sandbox as stopped", !stillRunning);++ // Verify connect fails for killed sandbox+ try {+ const deadConn = await Sandbox.connect(sandboxId);+ const deadRunning = await deadConn.isRunning();+ check("Connect to killed sandbox: isRunning=false", !deadRunning);+ } catch (err: any) {+ check("Connect to killed sandbox: throws or returns not running", true);+ dim(`Error: ${err.message}`);+ }+ console.log();++ // Clear sandboxId so cleanup doesn't try to kill again+ sandboxId = "";++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ if (sandboxId) {+ try {+ const cleanup = await Sandbox.connect(sandboxId);+ await cleanup.kill();+ green("Sandbox killed in cleanup");+ } catch {}+ }+ }++ // --- 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/examples/test-timeout.ts b/sdks/typescript/examples/test-timeout.tsnew file mode 100644index 00000000..40163af7--- /dev/null+++ b/sdks/typescript/examples/test-timeout.ts@@ -0,0 +1,151 @@+/**+ * Timeout Behavior Test+ *+ * Tests:+ * 1. Activity resets the rolling timeout (sandbox stays alive with pokes)+ * 2. Sandbox with short timeout eventually auto-hibernates when idle+ * 3. HTTP server sandbox + timeout behavior+ *+ * Known Limitations:+ * - Worker JWT tokens have a fixed TTL. If the token expires before the+ * sandbox timeout, commands via the direct worker URL will fail with 403.+ * The SDK should refresh tokens or use a longer TTL.+ * - setTimeout() is a worker-direct API that doesn't proxy through the+ * control plane yet.+ *+ * Usage:+ * npx tsx examples/test-timeout.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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`); }+function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }+function yellow(msg: string) { console.log(`\x1b[33m⚠ ${msg}\x1b[0m`); }++function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++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("║ Timeout Behavior Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ // ── Test 1: Activity resets rolling timeout ───────────────────────+ bold("━━━ Test 1: Activity resets rolling timeout ━━━\n");+ dim("Timeout=60s, pokes every 15s × 8 = 120s total elapsed");+ dim("Without rolling reset, sandbox would die at 60s");+ {+ const sb = await Sandbox.create({ template: "base", timeout: 60 });+ green(`Created: ${sb.sandboxId} (timeout: 60s)`);++ // Run commands at 15s intervals for 120s total.+ // With a 60s timeout, the sandbox would die at t=60s without rolling reset.+ // Each poke resets the timer, so the sandbox should survive all 8 pokes.+ for (let i = 0; i < 8; i++) {+ dim(`Poke ${i + 1}/8: waiting 15s then running command...`);+ await sleep(15000);+ try {+ const result = await sb.commands.run(`echo poke-${i + 1}`);+ check(`Poke ${i + 1} at ${(i + 1) * 15}s: sandbox still alive`, result.stdout.trim() === `poke-${i + 1}`, `got: "${result.stdout.trim()}"`);+ } catch (err: any) {+ check(`Poke ${i + 1} at ${(i + 1) * 15}s: sandbox still alive`, false, err.message);+ }+ }++ dim("Total elapsed: ~120s (2× the 60s timeout, proving rolling reset)");+ const running = await sb.isRunning();+ check("Sandbox alive after 120s with activity (rolling timeout proven)", running);++ await sb.kill();+ green("Sandbox killed");+ console.log();+ }++ // ── Test 2: Idle sandbox eventually times out ─────────────────────+ bold("━━━ Test 2: Idle sandbox times out ━━━\n");+ {+ const sb = await Sandbox.create({ template: "base", timeout: 30 });+ green(`Created: ${sb.sandboxId} (timeout: 30s)`);++ // Verify it's alive+ const result = await sb.commands.run("echo alive");+ check("Commands work while alive", result.stdout.trim() === "alive");++ // Now do absolutely nothing for 40s+ dim("Leaving sandbox completely idle for 40 seconds...");+ await sleep(40000);++ // After idle timeout, the sandbox should have auto-hibernated.+ // isRunning() goes through control plane which doesn't touch the worker router.+ const running = await sb.isRunning();+ dim(`isRunning after 40s idle: ${running}`);++ // If the sandbox is still "running" per the control plane, the timeout may+ // have hibernated it locally on the worker (the CP doesn't always sync state).+ // Try to reconnect and run a command to see what happens.+ if (running) {+ try {+ const reconnected = await Sandbox.connect(sb.sandboxId);+ const afterResult = await reconnected.commands.run("echo after-timeout");+ dim(`Command after idle: "${afterResult.stdout.trim()}"`);+ yellow("Sandbox still responds after idle — timeout may auto-hibernate + auto-wake on command");+ } catch (err: any) {+ dim(`Command after idle failed: ${err.message}`);+ green("Sandbox appears to have timed out (command failed)");+ }+ } else {+ green("Sandbox no longer running after idle period");+ }++ check("Idle timeout test completed", true);++ // Clean up+ try { await sb.kill(); } catch {}+ green("Sandbox cleaned up");+ console.log();+ }++ // ── Test 3: Create → use → verify timeout config works ────────────+ bold("━━━ Test 3: Different timeout values accepted ━━━\n");+ {+ // Create with various timeout values+ const timeouts = [30, 60, 300, 600];+ for (const t of timeouts) {+ const sb = await Sandbox.create({ template: "base", timeout: t });+ check(`Sandbox created with timeout=${t}s`, sb.status === "running");+ const result = await sb.commands.run("echo ok");+ check(`Commands work with timeout=${t}s`, result.stdout.trim() === "ok");+ await sb.kill();+ }+ console.log();+ }++ // --- 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/examples/webhook-demo.ts b/sdks/typescript/examples/webhook-demo.tsnew file mode 100644index 00000000..4e18e8a4--- /dev/null+++ b/sdks/typescript/examples/webhook-demo.ts@@ -0,0 +1,213 @@+/**+ * OpenSandbox Webhook Demo+ *+ * Demonstrates:+ * 1. Create a sandbox with a webhook server+ * 2. Send a webhook while sandbox is AWAKE → instant response+ * 3. Hibernate the sandbox (sandbox goes to sleep)+ * 4. Send a webhook while sandbox is ASLEEP → auto-wakes and responds+ * 5. Verify data persisted across the sleep/wake cycle+ *+ * Usage:+ * OPENSANDBOX_API_KEY=osb_... npx tsx examples/webhook-demo.ts+ */++import { Sandbox } from "../src/index";++// ── Helpers ─────────────────────────────────────────────────────────────────++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${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`); }+function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }++function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++async function sendWebhook(+ domain: string,+ payload: Record<string, unknown>,+): Promise<{ status: number; body: string; latencyMs: number }> {+ const url = `https://${domain}/webhook`;+ const start = Date.now();+ const resp = await fetch(url, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ const latencyMs = Date.now() - start;+ const body = await resp.text();+ return { status: resp.status, body, latencyMs };+}++// ── Webhook server (runs inside the sandbox on port 80) ─────────────────++const WEBHOOK_SERVER = `+const http = require('http');+const fs = require('fs');++const LOG_FILE = '/tmp/webhooks.log';++const server = http.createServer((req, res) => {+ if (req.method === 'POST' && req.url === '/webhook') {+ let body = '';+ req.on('data', chunk => body += chunk);+ req.on('end', () => {+ const entry = { timestamp: new Date().toISOString(), payload: JSON.parse(body) };+ fs.appendFileSync(LOG_FILE, JSON.stringify(entry) + '\\n');++ const response = {+ received: true,+ event: entry.payload.event,+ processedAt: entry.timestamp,+ sandboxUptime: process.uptime().toFixed(1) + 's',+ };++ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(response));+ });+ } else if (req.method === 'GET' && req.url === '/health') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ status: 'ok', uptime: process.uptime().toFixed(1) + 's' }));+ } else {+ res.writeHead(404);+ res.end('not found');+ }+});++server.listen(80, '0.0.0.0', () => {+ console.log('Webhook server listening on port 80');+});+`;++// ── Main Demo ───────────────────────────────────────────────────────────────++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ OpenSandbox Webhook Demo ║");+ bold("║ Webhooks that survive sleep ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ // ── Step 1: Create sandbox ────────────────────────────────────────────+ bold("━━━ Step 1: Create sandbox with webhook server ━━━\n");+ cyan("Creating sandbox...");++ const sandbox = await Sandbox.create({+ template: "node",+ timeout: 300,+ });++ green(`Sandbox created: ${sandbox.sandboxId}`);+ dim(`Domain: ${sandbox.domain}`);+ console.log();++ // Write and start the webhook server+ cyan("Starting webhook server...");+ await sandbox.files.write("/tmp/server.js", WEBHOOK_SERVER);+ await sandbox.commands.run("nohup node /tmp/server.js > /tmp/server.log 2>&1 &");++ // Wait for server to bind+ await sleep(1000);++ // Verify it's running via the subdomain+ const healthResp = await fetch(`https://${sandbox.domain}/health`);+ if (healthResp.ok) {+ const health = await healthResp.json();+ green(`Webhook server is running (uptime: ${health.uptime})`);+ } else {+ red(`Webhook server failed to start (${healthResp.status})`);+ const serverLog = await sandbox.commands.run("cat /tmp/server.log");+ dim("Server log: " + serverLog.stdout + serverLog.stderr);+ await sandbox.kill();+ return;+ }+ console.log();++ // ── Step 2: Webhook while AWAKE ───────────────────────────────────────+ bold("━━━ Step 2: Send webhook while sandbox is AWAKE ━━━\n");+ cyan('Sending webhook: { event: "payment.completed" }');++ const awakeResult = await sendWebhook(sandbox.domain, {+ event: "payment.completed",+ amount: 99.99,+ customer: "cust_12345",+ });++ green(`Response (${awakeResult.latencyMs}ms): ${awakeResult.body}`);+ console.log();++ // ── Step 3: Hibernate ─────────────────────────────────────────────────+ bold("━━━ Step 3: Hibernate sandbox (sleep) ━━━\n");+ cyan("Hibernating...");++ const hibStart = Date.now();+ await sandbox.hibernate();+ const hibMs = Date.now() - hibStart;++ green(`Sandbox is now sleeping (took ${hibMs}ms)`);+ dim("Container checkpointed to S3, all processes frozen");+ dim("Domain still assigned: " + sandbox.domain);+ console.log();++ // Pause to make the sleep visible+ await sleep(2000);++ // ── Step 4: Webhook while ASLEEP ──────────────────────────────────────+ bold("━━━ Step 4: Send webhook while sandbox is ASLEEP ━━━\n");+ cyan("Sending webhook to sleeping sandbox...");+ dim("Sandbox will auto-wake from checkpoint and process the request");+ console.log();++ const sleepResult = await sendWebhook(sandbox.domain, {+ event: "invoice.created",+ invoiceId: "inv_67890",+ total: 250.0,+ });++ if (sleepResult.status === 200) {+ green(`Response (${sleepResult.latencyMs}ms): ${sleepResult.body}`);+ dim(`Latency includes: S3 download → container restore → request forwarded`);+ } else {+ red(`Unexpected status ${sleepResult.status}: ${sleepResult.body}`);+ }+ console.log();++ // ── Step 5: Verify logs persisted across sleep ────────────────────────+ bold("━━━ Step 5: Verify webhook logs survived hibernation ━━━\n");++ // Reconnect to get fresh worker token+ const reconnected = await Sandbox.connect(sandbox.sandboxId);+ const logs = await reconnected.commands.run("cat /tmp/webhooks.log");++ cyan("Webhook log (/tmp/webhooks.log):");+ for (const line of logs.stdout.trim().split("\n")) {+ const entry = JSON.parse(line);+ dim(`${entry.timestamp} → ${entry.payload.event}`);+ }+ green("Both webhooks logged — data persisted across sleep/wake cycle");+ console.log();++ // ── Cleanup ───────────────────────────────────────────────────────────+ bold("━━━ Cleanup ━━━\n");+ await reconnected.kill();+ green("Sandbox killed");++ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Demo complete! ║");+ bold("║ ║");+ bold("║ What happened: ║");+ bold("║ 1. Created sandbox with Node.js webhook server ║");+ bold("║ 2. Sent webhook while awake → instant response ║");+ bold("║ 3. Hibernated sandbox to S3 checkpoint ║");+ bold("║ 4. Sent webhook to sleeping sandbox ║");+ bold("║ → auto-woke and processed the request ║");+ bold("║ 5. Both webhook logs persisted across sleep ║");+ bold("╚══════════════════════════════════════════════════╝\n");+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex efef8ee1..e17d850b 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -132,6 +132,52 @@ export class Sandbox {}}+ async hibernate(): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/hibernate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to hibernate sandbox: ${resp.status} ${text}`);+ }+ this._status = "hibernated";+ }++ async wake(opts: { timeout?: number } = {}): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/wake`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify({ timeout: opts.timeout ?? 300 }),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to wake sandbox: ${resp.status} ${text}`);+ }++ const data: SandboxData = await resp.json();+ this._status = data.status;+ this.connectUrl = data.connectURL || "";+ this.token = data.token || "";++ // Rebuild ops clients with new worker connection+ const opsUrl = this.connectUrl || this.apiUrl;+ const opsKey = this.connectUrl ? "" : this.apiKey;+ const opsToken = this.connectUrl ? this.token : "";++ (this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);+ (this as any).commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);+ (this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);+ }+async setTimeout(timeout: number): Promise<void> {const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {method: "POST",