An open-source, faster Devin alternative
TypeScript
add patching on wake
Brian Reardonf919bf839ff9
diff --git a/internal/api/router.go b/internal/api/router.goindex 2b4611b1..6425ba52 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -142,6 +142,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/from-checkpoint/:checkpointId", s.createFromCheckpoint)api.DELETE("/sandboxes/:id/checkpoints/:checkpointId", s.deleteCheckpoint)+ // Checkpoint patches+ api.POST("/sandboxes/checkpoints/:checkpointId/patches", s.createCheckpointPatch)+ api.GET("/sandboxes/checkpoints/:checkpointId/patches", s.listCheckpointPatches)+// Preview URLs (on-demand port-based)api.POST("/sandboxes/:id/preview", s.createPreviewURL)api.GET("/sandboxes/:id/preview", s.listPreviewURLs)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 88c6d831..9251c073 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -662,6 +662,9 @@ func (s *Server) wakeSandbox(c echo.Context) error {_ = s.store.MarkHibernationRestored(ctx, id)_ = s.store.UpdateSandboxSessionForWake(ctx, id, s.workerID)+ // Apply pending checkpoint patches in background+ go s.applyPendingPatches(id, s.workerID)+// Issue fresh JWTorgID, _ := auth.GetOrgID(c)if s.jwtIssuer != nil {@@ -723,6 +726,9 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W_ = s.store.MarkHibernationRestored(c.Request().Context(), sandboxID)_ = s.store.UpdateSandboxSessionForWake(c.Request().Context(), sandboxID, worker.ID)+ // Apply pending checkpoint patches in background+ go s.applyPendingPatches(sandboxID, worker.ID)+// Issue fresh JWTorgID, _ := auth.GetOrgID(c)timeout := req.Timeout@@ -1097,6 +1103,8 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {cfgJSON, _ := json.Marshal(originalCfg)metadataJSON, _ := json.Marshal(originalCfg.Metadata)_, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, nil, template, region, workerID, cfgJSON, metadataJSON)+ // Track checkpoint lineage for patch system+ _ = s.store.SetSandboxCheckpointID(ctx, sandboxID, checkpointID)}// Boot VM in background@@ -1151,6 +1159,11 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {if s.router != nil {s.router.MarkCreated(sandboxID, createErr)}++ // Apply any existing patches for this checkpoint after boot+ if createErr == nil {+ s.applyPendingPatches(sandboxID, workerID)+ }}()return c.JSON(http.StatusCreated, map[string]interface{}{@@ -1213,6 +1226,229 @@ func (s *Server) deleteCheckpoint(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+// --- Checkpoint Patch handlers ---++// createCheckpointPatch creates a patch for a checkpoint and fans out to running sandboxes.+func (s *Server) createCheckpointPatch(c echo.Context) error {+ checkpointIDStr := c.Param("checkpointId")+ ctx := c.Request().Context()++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ // Verify checkpoint exists and belongs to org+ cp, err := s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "checkpoint does not belong to this organization"})+ }+ if cp.Status != "ready" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready"})+ }++ var req struct {+ Script string `json:"script"`+ Description string `json:"description"`+ Strategy string `json:"strategy"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})+ }+ if req.Script == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "script is required"})+ }+ if req.Strategy == "" {+ req.Strategy = "hot"+ }+ if req.Strategy != "hot" && req.Strategy != "on_wake" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "strategy must be 'hot' or 'on_wake'"})+ }++ // Create the patch record+ patch := &db.CheckpointPatch{+ ID: uuid.New(),+ CheckpointID: checkpointID,+ Script: req.Script,+ Description: req.Description,+ Strategy: req.Strategy,+ }+ if err := s.store.CreateCheckpointPatch(ctx, patch); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create patch: " + err.Error()})+ }++ // Fan out to running sandboxes if strategy is "hot"+ var results struct {+ Total int `json:"total"`+ RunningPatched int `json:"runningPatched"`+ RunningFailed int `json:"runningFailed"`+ HibernatedQueued int `json:"hibernatedQueued"`+ }++ sandboxes, err := s.store.ListSandboxesByCheckpoint(ctx, checkpointID)+ if err != nil {+ log.Printf("api: patch %s: failed to list sandboxes: %v", patch.ID, err)+ } else {+ results.Total = len(sandboxes)++ for _, sess := range sandboxes {+ if sess.Status == "hibernated" {+ results.HibernatedQueued+++ continue+ }++ if sess.Status == "running" && req.Strategy == "hot" {+ // Execute patch on running sandbox+ if err := s.execPatchOnSandbox(ctx, sess.SandboxID, sess.WorkerID, patch); err != nil {+ log.Printf("api: patch %s: sandbox %s failed: %v", patch.ID, sess.SandboxID, err)+ results.RunningFailed+++ } else {+ results.RunningPatched+++ _ = s.store.UpdateSandboxPatchSequence(ctx, sess.SandboxID, patch.Sequence)+ }+ }+ }+ }++ return c.JSON(http.StatusCreated, map[string]interface{}{+ "patch": patch,+ "results": results,+ })+}++// execPatchOnSandbox runs a patch script on a running sandbox via gRPC exec.+func (s *Server) execPatchOnSandbox(ctx context.Context, sandboxID, workerID string, patch *db.CheckpointPatch) error {+ execCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)+ defer cancel()++ if s.workerRegistry != nil {+ client, err := s.workerRegistry.GetWorkerClient(workerID)+ if err != nil {+ return fmt.Errorf("worker %s unreachable: %w", workerID, err)+ }+ resp, err := client.ExecCommand(execCtx, &pb.ExecCommandRequest{+ SandboxId: sandboxID,+ Command: "bash",+ Args: []string{"-c", patch.Script},+ Timeout: 300,+ })+ if err != nil {+ return fmt.Errorf("exec failed: %w", err)+ }+ if resp.ExitCode != 0 {+ return fmt.Errorf("patch exited with code %d: %s", resp.ExitCode, resp.Stderr)+ }+ return nil+ }++ // Combined mode: exec locally+ if s.manager != nil {+ result, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{+ Command: "bash",+ Args: []string{"-c", patch.Script},+ Timeout: 300,+ })+ if err != nil {+ return fmt.Errorf("exec failed: %w", err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("patch exited with code %d: %s", result.ExitCode, result.Stderr)+ }+ return nil+ }++ return fmt.Errorf("no execution backend available")+}++// applyPendingPatches checks for and applies any pending patches after a sandbox wakes.+func (s *Server) applyPendingPatches(sandboxID, workerID string) {+ if s.store == nil {+ return+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)+ defer cancel()++ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ log.Printf("patches: %s: failed to get session: %v", sandboxID, err)+ return+ }+ if session.BasedOnCheckpointID == nil {+ return // Not based on a checkpoint, nothing to patch+ }++ patches, err := s.store.GetPendingPatches(ctx, *session.BasedOnCheckpointID, session.LastPatchSequence)+ if err != nil {+ log.Printf("patches: %s: failed to get pending patches: %v", sandboxID, err)+ return+ }+ if len(patches) == 0 {+ return+ }++ log.Printf("patches: %s: applying %d pending patches (from seq %d)", sandboxID, len(patches), session.LastPatchSequence+1)++ for _, patch := range patches {+ if err := s.execPatchOnSandbox(ctx, sandboxID, workerID, &patch); err != nil {+ log.Printf("patches: %s: patch seq %d failed: %v (stopping)", sandboxID, patch.Sequence, err)+ return // Stop on first failure+ }+ _ = s.store.UpdateSandboxPatchSequence(ctx, sandboxID, patch.Sequence)+ log.Printf("patches: %s: patch seq %d applied successfully", sandboxID, patch.Sequence)+ }+}++// listCheckpointPatches returns all patches for a checkpoint.+func (s *Server) listCheckpointPatches(c echo.Context) error {+ checkpointIDStr := c.Param("checkpointId")++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ // Verify checkpoint belongs to org+ cp, err := s.store.GetCheckpoint(c.Request().Context(), checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "checkpoint does not belong to this organization"})+ }++ patches, err := s.store.ListCheckpointPatches(c.Request().Context(), checkpointID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ if patches == nil {+ patches = []db.CheckpointPatch{}+ }++ return c.JSON(http.StatusOK, patches)+}+// listSessions returns session history from PostgreSQL.func (s *Server) listWorkers(c echo.Context) error {if s.workerRegistry == nil {diff --git a/internal/db/migrations/013_checkpoint_patches.up.sql b/internal/db/migrations/013_checkpoint_patches.up.sqlnew file mode 100644index 00000000..471d2a9f--- /dev/null+++ b/internal/db/migrations/013_checkpoint_patches.up.sql@@ -0,0 +1,16 @@+-- Patch scripts attached to checkpoints for rolling updates+CREATE TABLE checkpoint_patches (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ checkpoint_id UUID NOT NULL REFERENCES sandbox_checkpoints(id) ON DELETE CASCADE,+ sequence INT NOT NULL,+ script TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ strategy TEXT NOT NULL DEFAULT 'hot', -- hot | on_wake+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE(checkpoint_id, sequence)+);+CREATE INDEX idx_checkpoint_patches_checkpoint ON checkpoint_patches(checkpoint_id, sequence);++-- Track which checkpoint a sandbox was forked from + patch level+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS based_on_checkpoint_id UUID REFERENCES sandbox_checkpoints(id);+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS last_patch_sequence INT NOT NULL DEFAULT 0;diff --git a/internal/db/store.go b/internal/db/store.goindex 479c5af8..f7b5c2ac 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -76,6 +76,7 @@ func (s *Store) Migrate(ctx context.Context) error {{10, "migrations/010_template_status.up.sql"},{11, "migrations/011_rename_hibernation.up.sql"},{12, "migrations/012_checkpoints.up.sql"},+ {13, "migrations/013_checkpoint_patches.up.sql"},}for _, m := range migrations {@@ -380,19 +381,21 @@ func (s *Store) DeleteAPIKeyForOrg(ctx context.Context, id uuid.UUID, orgID uuid// --- Sandbox Session operations ---type SandboxSession struct {- ID uuid.UUID `json:"id"`- SandboxID string `json:"sandboxId"`- OrgID uuid.UUID `json:"orgId"`- UserID *uuid.UUID `json:"userId,omitempty"`- Template string `json:"template"`- Region string `json:"region"`- WorkerID string `json:"workerId"`- Status string `json:"status"`- Config json.RawMessage `json:"config"`- Metadata json.RawMessage `json:"metadata,omitempty"`- StartedAt time.Time `json:"startedAt"`- StoppedAt *time.Time `json:"stoppedAt,omitempty"`- ErrorMsg *string `json:"errorMsg,omitempty"`+ ID uuid.UUID `json:"id"`+ SandboxID string `json:"sandboxId"`+ OrgID uuid.UUID `json:"orgId"`+ UserID *uuid.UUID `json:"userId,omitempty"`+ Template string `json:"template"`+ Region string `json:"region"`+ WorkerID string `json:"workerId"`+ Status string `json:"status"`+ Config json.RawMessage `json:"config"`+ Metadata json.RawMessage `json:"metadata,omitempty"`+ StartedAt time.Time `json:"startedAt"`+ StoppedAt *time.Time `json:"stoppedAt,omitempty"`+ ErrorMsg *string `json:"errorMsg,omitempty"`+ BasedOnCheckpointID *uuid.UUID `json:"basedOnCheckpointId,omitempty"`+ LastPatchSequence int `json:"lastPatchSequence"`}func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage) (*SandboxSession, error) {@@ -400,10 +403,11 @@ func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgIerr := s.pool.QueryRow(ctx,`INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata)VALUES ($1, $2, $3, $4, $5, $6, $7, $8)- RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at`,+ RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, based_on_checkpoint_id, last_patch_sequence`,sandboxID, orgID, userID, template, region, workerID, config, metadata,).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,- &session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata, &session.StartedAt)+ &session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata, &session.StartedAt,+ &session.BasedOnCheckpointID, &session.LastPatchSequence)if err != nil {return nil, fmt.Errorf("failed to create sandbox session: %w", err)}@@ -434,11 +438,11 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statufunc (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {session := &SandboxSession{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequenceFROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`, sandboxID,).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,- &session.StartedAt, &session.StoppedAt, &session.ErrorMsg)+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence)if err != nil {return nil, fmt.Errorf("sandbox session not found: %w", err)}@@ -450,12 +454,12 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusvar err errorif status != "" {rows, err = s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequenceFROM sandbox_sessions WHERE org_id = $1 AND status = $2 ORDER BY started_at DESC LIMIT $3 OFFSET $4`,orgID, status, limit, offset)} else {rows, err = s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequenceFROM sandbox_sessions WHERE org_id = $1 ORDER BY started_at DESC LIMIT $2 OFFSET $3`,orgID, limit, offset)}@@ -469,7 +473,7 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusvar sess SandboxSessionif err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,&sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,- &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg); err != nil {+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence); err != nil {return nil, err}sessions = append(sessions, sess)@@ -833,6 +837,112 @@ func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpoinreturn nil}+// --- Checkpoint Patch operations ---++// CheckpointPatch represents a patch script attached to a checkpoint.+type CheckpointPatch struct {+ ID uuid.UUID `json:"id"`+ CheckpointID uuid.UUID `json:"checkpointId"`+ Sequence int `json:"sequence"`+ Script string `json:"script"`+ Description string `json:"description"`+ Strategy string `json:"strategy"`+ CreatedAt time.Time `json:"createdAt"`+}++// CreateCheckpointPatch inserts a new patch, auto-assigning the next sequence number.+func (s *Store) CreateCheckpointPatch(ctx context.Context, patch *CheckpointPatch) error {+ return s.pool.QueryRow(ctx,+ `INSERT INTO checkpoint_patches (id, checkpoint_id, sequence, script, description, strategy)+ VALUES ($1, $2, COALESCE((SELECT MAX(sequence) FROM checkpoint_patches WHERE checkpoint_id = $2), 0) + 1, $3, $4, $5)+ RETURNING sequence, created_at`,+ patch.ID, patch.CheckpointID, patch.Script, patch.Description, patch.Strategy,+ ).Scan(&patch.Sequence, &patch.CreatedAt)+}++// ListCheckpointPatches returns all patches for a checkpoint, ordered by sequence.+func (s *Store) ListCheckpointPatches(ctx context.Context, checkpointID uuid.UUID) ([]CheckpointPatch, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, checkpoint_id, sequence, script, description, strategy, created_at+ FROM checkpoint_patches WHERE checkpoint_id = $1 ORDER BY sequence ASC`, checkpointID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var patches []CheckpointPatch+ for rows.Next() {+ var p CheckpointPatch+ if err := rows.Scan(&p.ID, &p.CheckpointID, &p.Sequence, &p.Script, &p.Description, &p.Strategy, &p.CreatedAt); err != nil {+ return nil, err+ }+ patches = append(patches, p)+ }+ return patches, rows.Err()+}++// GetPendingPatches returns patches with sequence > afterSequence for a checkpoint.+func (s *Store) GetPendingPatches(ctx context.Context, checkpointID uuid.UUID, afterSequence int) ([]CheckpointPatch, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, checkpoint_id, sequence, script, description, strategy, created_at+ FROM checkpoint_patches WHERE checkpoint_id = $1 AND sequence > $2 ORDER BY sequence ASC`,+ checkpointID, afterSequence)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var patches []CheckpointPatch+ for rows.Next() {+ var p CheckpointPatch+ if err := rows.Scan(&p.ID, &p.CheckpointID, &p.Sequence, &p.Script, &p.Description, &p.Strategy, &p.CreatedAt); err != nil {+ return nil, err+ }+ patches = append(patches, p)+ }+ return patches, rows.Err()+}++// UpdateSandboxPatchSequence updates the last_patch_sequence for a sandbox session.+func (s *Store) UpdateSandboxPatchSequence(ctx context.Context, sandboxID string, sequence int) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET last_patch_sequence = $1 WHERE sandbox_id = $2`,+ sequence, sandboxID)+ return err+}++// SetSandboxCheckpointID sets the based_on_checkpoint_id for a sandbox session.+func (s *Store) SetSandboxCheckpointID(ctx context.Context, sandboxID string, checkpointID uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET based_on_checkpoint_id = $1 WHERE sandbox_id = $2`,+ checkpointID, sandboxID)+ return err+}++// ListSandboxesByCheckpoint returns all non-stopped sandboxes forked from a checkpoint.+func (s *Store) ListSandboxesByCheckpoint(ctx context.Context, checkpointID uuid.UUID) ([]SandboxSession, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence+ FROM sandbox_sessions WHERE based_on_checkpoint_id = $1 AND status IN ('running', 'hibernated') ORDER BY started_at DESC`,+ checkpointID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var sessions []SandboxSession+ for rows.Next() {+ var sess SandboxSession+ if err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,+ &sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence); err != nil {+ return nil, err+ }+ sessions = append(sessions, sess)+ }+ return sessions, rows.Err()+}+// --- Template operations ---// DBTemplate represents a template record in the database.diff --git a/sdks/typescript/examples/test-checkpoint-patches.ts b/sdks/typescript/examples/test-checkpoint-patches.tsnew file mode 100644index 00000000..ffdef252--- /dev/null+++ b/sdks/typescript/examples/test-checkpoint-patches.ts@@ -0,0 +1,261 @@+/**+ * Checkpoint Patch System Test+ *+ * Tests:+ * 1. Create a sandbox, checkpoint it, fork 2 sandboxes from it+ * 2. Create a "hot" patch on the checkpoint (should exec on running sandboxes)+ * 3. Verify the patch was applied to both running forks+ * 4. Create a third fork — verify existing patches are applied on boot+ * 5. Create an "on_wake" patch+ * 6. Hibernate a fork, wake it, verify on_wake patch was applied+ * 7. List patches and verify ordering+ * 8. Verify patch failure handling (bad script)+ *+ * Usage:+ * npx tsx examples/test-checkpoint-patches.ts+ *+ * Environment:+ * OPENCOMPUTER_API_URL (default: https://app.opencomputer.dev)+ * OPENCOMPUTER_API_KEY (required)+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }++let passed = 0;+let failed = 0;++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) {+ green(desc);+ passed++;+ } else {+ red(`${desc}${detail ? ` (${detail})` : ""}`);+ failed++;+ }+}++async function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++async function waitForCheckpointReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 60000): Promise<boolean> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const checkpoints = await sandbox.listCheckpoints();+ const cp = checkpoints.find((c) => c.id === checkpointId);+ if (cp && cp.status === "ready") return true;+ if (cp && cp.status !== "processing") return false;+ await sleep(2000);+ }+ return false;+}++async function main() {+ bold("\n====================================================");+ bold(" Checkpoint Patch System Test");+ bold("====================================================\n");++ const sandboxes: Sandbox[] = [];++ try {+ // ── Setup: Create source sandbox with initial state ──────────+ bold("--- Setup: Create source sandbox and checkpoint ---\n");++ const source = await Sandbox.create({ template: "base", timeout: 600 });+ sandboxes.push(source);+ green(`Created source sandbox: ${source.sandboxId}`);++ // Install a marker to verify patch effects+ await source.commands.run("echo 'original' > /workspace/patch-marker.txt");+ await source.commands.run("echo 'python3.10' > /workspace/python-version.txt");+ const initial = await source.commands.run("cat /workspace/python-version.txt");+ check("Initial state set", initial.stdout.trim() === "python3.10");++ // Create checkpoint+ const cp = await source.createCheckpoint("patch-base");+ dim(`Checkpoint ID: ${cp.id}`);++ dim("Waiting for checkpoint to be ready...");+ const ready = await waitForCheckpointReady(source, cp.id);+ check("Checkpoint is ready", ready);+ if (!ready) throw new Error("Checkpoint not ready, cannot proceed");+ console.log();++ // ── Test 1: Fork 2 sandboxes from checkpoint ──────────────────+ bold("--- Test 1: Fork sandboxes from checkpoint ---\n");++ const fork1 = await Sandbox.createFromCheckpoint(cp.id, { timeout: 600 });+ sandboxes.push(fork1);+ green(`Fork 1 created: ${fork1.sandboxId}`);++ const fork2 = await Sandbox.createFromCheckpoint(cp.id, { timeout: 600 });+ sandboxes.push(fork2);+ green(`Fork 2 created: ${fork2.sandboxId}`);++ // Wait for forks to boot+ await sleep(5000);++ // Verify forks have the original state+ const f1State = await fork1.commands.run("cat /workspace/python-version.txt");+ check("Fork 1 has original state", f1State.stdout.trim() === "python3.10");+ const f2State = await fork2.commands.run("cat /workspace/python-version.txt");+ check("Fork 2 has original state", f2State.stdout.trim() === "python3.10");+ console.log();++ // ── Test 2: Create a "hot" patch ─────────────────────────────+ bold("--- Test 2: Create hot patch (should apply to running forks) ---\n");++ const patchResult = await Sandbox.createCheckpointPatch(cp.id, {+ script: "echo 'python3.11' > /workspace/python-version.txt && echo 'patched' > /workspace/patch-applied.txt",+ description: "Upgrade Python version marker",+ strategy: "hot",+ });++ check("Patch created", patchResult.patch.id !== undefined);+ check("Patch sequence is 1", patchResult.patch.sequence === 1);+ check("Patch strategy is hot", patchResult.patch.strategy === "hot");+ dim(`Patch ID: ${patchResult.patch.id}`);+ dim(`Results: total=${patchResult.results.total}, patched=${patchResult.results.runningPatched}, failed=${patchResult.results.runningFailed}, queued=${patchResult.results.hibernatedQueued}`);++ // The source sandbox is not forked from the checkpoint, so only fork1 and fork2 should be patched+ check("Running sandboxes were patched", patchResult.results.runningPatched >= 2, `got ${patchResult.results.runningPatched}`);+ check("No failures", patchResult.results.runningFailed === 0, `got ${patchResult.results.runningFailed}`);+ console.log();++ // ── Test 3: Verify patch was applied ─────────────────────────+ bold("--- Test 3: Verify patch applied to running forks ---\n");++ // Small delay for exec to complete+ await sleep(2000);++ const f1Patched = await fork1.commands.run("cat /workspace/python-version.txt");+ check("Fork 1 has patched state", f1Patched.stdout.trim() === "python3.11", `got: ${f1Patched.stdout.trim()}`);++ const f1Marker = await fork1.commands.run("cat /workspace/patch-applied.txt");+ check("Fork 1 has patch marker", f1Marker.stdout.trim() === "patched");++ const f2Patched = await fork2.commands.run("cat /workspace/python-version.txt");+ check("Fork 2 has patched state", f2Patched.stdout.trim() === "python3.11", `got: ${f2Patched.stdout.trim()}`);+ console.log();++ // ── Test 4: New fork gets existing patches applied ───────────+ bold("--- Test 4: New fork gets existing patches on boot ---\n");++ const fork3 = await Sandbox.createFromCheckpoint(cp.id, { timeout: 600 });+ sandboxes.push(fork3);+ green(`Fork 3 created: ${fork3.sandboxId}`);++ // Wait for boot + patch application+ await sleep(8000);++ const f3Patched = await fork3.commands.run("cat /workspace/python-version.txt");+ check("Fork 3 has patched state (applied on boot)", f3Patched.stdout.trim() === "python3.11", `got: ${f3Patched.stdout.trim()}`);++ const f3Marker = await fork3.commands.run("cat /workspace/patch-applied.txt");+ check("Fork 3 has patch marker", f3Marker.stdout.trim() === "patched", `got: ${f3Marker.stdout.trim()}`);+ console.log();++ // ── Test 5: Create "on_wake" patch ───────────────────────────+ bold("--- Test 5: Create on_wake patch ---\n");++ const patch2Result = await Sandbox.createCheckpointPatch(cp.id, {+ script: "echo 'security-fix-applied' > /workspace/security-patch.txt",+ description: "Security hotfix",+ strategy: "on_wake",+ });++ check("on_wake patch created", patch2Result.patch.id !== undefined);+ check("Patch sequence is 2", patch2Result.patch.sequence === 2);+ check("on_wake patch did NOT exec on running sandboxes", patch2Result.results.runningPatched === 0);+ dim(`Hibernated queued: ${patch2Result.results.hibernatedQueued}`);+ console.log();++ // Verify on_wake patch was NOT applied to running fork1+ const f1Security = await fork1.commands.run("test -f /workspace/security-patch.txt && echo exists || echo missing");+ check("on_wake patch not applied to running sandbox", f1Security.stdout.trim() === "missing");+ console.log();++ // ── Test 6: Hibernate + wake → on_wake patch applied ─────────+ bold("--- Test 6: Hibernate and wake fork (patches applied on wake) ---\n");++ dim("Hibernating fork 1...");+ await fork1.hibernate();+ green("Fork 1 hibernated");++ await sleep(3000);++ dim("Waking fork 1...");+ await fork1.wake({ timeout: 600 });+ green("Fork 1 woken");++ // Wait for post-wake patching+ await sleep(5000);++ const f1SecurityAfterWake = await fork1.commands.run("cat /workspace/security-patch.txt");+ check("on_wake patch applied after wake", f1SecurityAfterWake.stdout.trim() === "security-fix-applied", `got: ${f1SecurityAfterWake.stdout.trim()}`);++ // Verify prior patches still present+ const f1PythonAfterWake = await fork1.commands.run("cat /workspace/python-version.txt");+ check("Prior patch state preserved after wake", f1PythonAfterWake.stdout.trim() === "python3.11", `got: ${f1PythonAfterWake.stdout.trim()}`);+ console.log();++ // ── Test 7: List patches ─────────────────────────────────────+ bold("--- Test 7: List patches ---\n");++ const patches = await Sandbox.listCheckpointPatches(cp.id);+ check("2 patches listed", patches.length === 2, `got ${patches.length}`);+ check("First patch has sequence 1", patches[0]?.sequence === 1);+ check("Second patch has sequence 2", patches[1]?.sequence === 2);+ check("First patch is hot", patches[0]?.strategy === "hot");+ check("Second patch is on_wake", patches[1]?.strategy === "on_wake");+ console.log();++ // ── Test 8: Bad patch (should fail gracefully) ───────────────+ bold("--- Test 8: Bad patch script ---\n");++ const badPatch = await Sandbox.createCheckpointPatch(cp.id, {+ script: "exit 1",+ description: "Intentionally failing patch",+ strategy: "hot",+ });++ check("Bad patch created", badPatch.patch.id !== undefined);+ check("Bad patch sequence is 3", badPatch.patch.sequence === 3);+ // Running sandboxes should report failures+ check("Running sandboxes reported failures", badPatch.results.runningFailed > 0, `failed=${badPatch.results.runningFailed}`);+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ // Cleanup+ bold("--- Cleanup ---\n");+ for (const sb of sandboxes) {+ try {+ await sb.kill();+ green(`Killed ${sb.sandboxId}`);+ } catch {+ /* best effort */+ }+ }+ }++ // --- Summary ---+ 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/src/index.ts b/sdks/typescript/src/index.tsindex cde2dfd4..9b161035 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -1,4 +1,4 @@-export { Sandbox, type SandboxOpts, type CheckpointInfo } from "./sandbox.js";+export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type PatchResult } from "./sandbox.js";export { Filesystem, type EntryInfo } from "./filesystem.js";export { Commands, type ProcessResult, type RunOpts } from "./commands.js";export { Pty, type PtySession, type PtyOpts } from "./pty.js";diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 37af3501..7c228d00 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -39,6 +39,26 @@ export interface CheckpointInfo {createdAt: string;}+export interface PatchInfo {+ id: string;+ checkpointId: string;+ sequence: number;+ script: string;+ description: string;+ strategy: string;+ createdAt: string;+}++export interface PatchResult {+ patch: PatchInfo;+ results: {+ total: number;+ runningPatched: number;+ runningFailed: number;+ hibernatedQueued: number;+ };+}+export interface PreviewURLResult {id: string;sandboxId: string;@@ -315,6 +335,52 @@ export class Sandbox {}}+ static async createCheckpointPatch(+ checkpointId: string,+ opts: { script: string; description?: string; strategy?: "hot" | "on_wake"; apiKey?: string; apiUrl?: string }+ ): Promise<PatchResult> {+ const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");+ const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";++ const resp = await fetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(apiKey ? { "X-API-Key": apiKey } : {}),+ },+ body: JSON.stringify({+ script: opts.script,+ description: opts.description ?? "",+ strategy: opts.strategy ?? "hot",+ }),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to create checkpoint patch: ${resp.status} ${text}`);+ }++ return resp.json();+ }++ static async listCheckpointPatches(+ checkpointId: string,+ opts: { apiKey?: string; apiUrl?: string } = {}+ ): Promise<PatchInfo[]> {+ const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");+ const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";++ const resp = await fetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {+ headers: apiKey ? { "X-API-Key": apiKey } : {},+ });++ if (!resp.ok) {+ throw new Error(`Failed to list checkpoint patches: ${resp.status}`);+ }++ return resp.json();+ }+async createPreviewURL(opts: { port: number; domain?: string; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {method: "POST",