Skip to content

An open-source, faster Devin alternative

TypeScript

make second endpoints, preserve compat

Brian Reardon57db1779dc3b
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 03585f94..84e2879e 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -233,14 +233,9 @@ func (s *Server) execRun(c echo.Context) error {
return s.execRunRemote(c, id, req)
}
- // Async path (QEMU worker): run the command as a background exec session
- // and return a handle immediately. The caller polls GET /exec/:execId/result
- // for completion. Every HTTP request stays sub-second, so the edge proxy
- // never 524s no matter how long the command runs.
- if s.execSessionManager != nil {
- return s.execRunAsync(c, id, req)
- }
-
+ // POST /exec/run is the synchronous one-shot endpoint, kept for SDK versions
+ // that predate the async flow. Newer SDKs POST /exec/run-async, which returns
+ // a handle immediately and is polled via /result (see execRunAsyncRoute).
if s.manager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -270,6 +265,26 @@ func (s *Server) execRun(c echo.Context) error {
return c.JSON(http.StatusOK, result)
}
+// execRunAsyncRoute handles POST /exec/run-async — the async exec entrypoint.
+// It binds the request and dispatches a background exec session, returning a
+// handle immediately. Newer SDKs poll GET /exec/:execId/result for completion;
+// POST /exec/run stays synchronous for older SDKs.
+func (s *Server) execRunAsyncRoute(c echo.Context) error {
+ id := c.Param("id")
+
+ var req types.ProcessConfig
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if req.Command == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
+ }
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+ return s.execRunAsync(c, id, req)
+}
+
// execRunRemote routes an exec/run request to the worker via gRPC.
func (s *Server) execRunRemote(c echo.Context, sandboxID string, req types.ProcessConfig) error {
orgID, _ := auth.GetOrgID(c)
diff --git a/internal/api/router.go b/internal/api/router.go
index 163c2f60..76db323b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -507,6 +507,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes/:id/exec/:sessionID/result", pxy)
api.POST("/sandboxes/:id/exec/:sessionID/kill", pxy)
api.POST("/sandboxes/:id/exec/run", pxy)
+ api.POST("/sandboxes/:id/exec/run-async", pxy)
// Agent
api.POST("/sandboxes/:id/agent", pxy)
@@ -547,6 +548,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes/:id/exec/:sessionID/result", s.execResult)
api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
api.POST("/sandboxes/:id/exec/run", s.execRun)
+ api.POST("/sandboxes/:id/exec/run-async", s.execRunAsyncRoute)
api.POST("/sandboxes/:id/agent", s.createAgentSession)
api.GET("/sandboxes/:id/agent", s.listAgentSessions)
diff --git a/internal/api/snapshots.go b/internal/api/snapshots.go
index bda72b11..8b088b3c 100644
--- a/internal/api/snapshots.go
+++ b/internal/api/snapshots.go
@@ -14,15 +14,19 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
)
-// createSnapshot handles POST /api/snapshots — creates a pre-built named snapshot from a declarative image.
-func (s *Server) createSnapshot(c echo.Context) error {
+// parseSnapshotCreate validates the shared POST body for the snapshot create
+// endpoints (auth, name, image, name-uniqueness). On any failure it writes the
+// error response and returns ok=false; the caller should then `return nil`.
+func (s *Server) parseSnapshotCreate(c echo.Context) (orgID uuid.UUID, name string, image json.RawMessage, ok bool) {
if s.store == nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ _ = c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ return uuid.Nil, "", nil, false
}
- orgID, ok := auth.GetOrgID(c)
- if !ok {
- return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ oid, found := auth.GetOrgID(c)
+ if !found {
+ _ = c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ return uuid.Nil, "", nil, false
}
var req struct {
@@ -30,35 +34,68 @@ func (s *Server) createSnapshot(c echo.Context) error {
Image json.RawMessage `json:"image"`
}
if err := c.Bind(&req); err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ _ = c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ return uuid.Nil, "", nil, false
}
-
if req.Name == "" {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
+ _ = c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
+ return uuid.Nil, "", nil, false
}
if len(req.Image) == 0 {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "image is required"})
+ _ = c.JSON(http.StatusBadRequest, map[string]string{"error": "image is required"})
+ return uuid.Nil, "", nil, false
}
- ctx := c.Request().Context()
-
// Check if name is already taken
- existing, err := s.store.GetImageCacheByName(ctx, orgID, req.Name)
+ existing, err := s.store.GetImageCacheByName(c.Request().Context(), oid, req.Name)
if err == nil && existing != nil {
- return c.JSON(http.StatusConflict, map[string]string{"error": "snapshot name already exists"})
+ _ = c.JSON(http.StatusConflict, map[string]string{"error": "snapshot name already exists"})
+ return uuid.Nil, "", nil, false
+ }
+
+ return oid, req.Name, req.Image, true
+}
+
+// createSnapshot handles POST /api/snapshots — creates a pre-built named
+// snapshot from a declarative image.
+//
+// Three shapes, picked by the request:
+// - Accept: text/event-stream → SSE build-log stream (unchanged).
+// - ?async=1 → non-blocking: returns a "building" row immediately and builds
+// in the background; the caller polls GET /snapshots/:name until
+// ready|failed. Newer clients use this to avoid a 524 on a long build.
+// - otherwise → synchronous build that blocks until the snapshot is ready,
+// preserving the original contract for SDK versions that predate the async
+// flow.
+//
+// async is a query param rather than a /snapshots/async subpath because the edge
+// router treats any /api/snapshots/<seg> as a snapshot named <seg>.
+func (s *Server) createSnapshot(c echo.Context) error {
+ orgID, name, image, ok := s.parseSnapshotCreate(c)
+ if !ok {
+ return nil
}
+ ctx := c.Request().Context()
+
// SSE streaming path
if c.Request().Header.Get("Accept") == "text/event-stream" {
- return s.createSnapshotWithSSE(c, ctx, orgID, req.Name, req.Image)
+ return s.createSnapshotWithSSE(c, ctx, orgID, name, image)
}
- // Non-streaming path: build asynchronously. Pre-create the named snapshot
- // row as "building" and run the (potentially multi-minute) build in the
- // background, returning immediately. Callers poll GET /snapshots/:name until
- // status is "ready" or "failed". This keeps the request sub-second so the
- // edge proxy never 524s on a long build.
- return s.createSnapshotAsync(c, orgID, req.Name, req.Image)
+ // Async (non-blocking) opt-in.
+ if c.QueryParam("async") == "1" {
+ return s.createSnapshotAsync(c, orgID, name, image)
+ }
+
+ // Non-streaming path: synchronous build (legacy contract).
+ ic, err := s.createSnapshotCore(ctx, orgID, name, image, nil)
+ if err != nil {
+ log.Printf("snapshot: build failed for %q: %v", name, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ log.Printf("snapshot: created %q", name)
+ return c.JSON(http.StatusCreated, ic)
}
// createSnapshotAsync pre-creates a named "building" snapshot row, dispatches
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
index 49910e13..0812e075 100644
--- a/internal/proxy/sandbox_api_proxy.go
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -279,12 +279,14 @@ func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {
}
// File ops are synchronous (the caller wants the bytes/result now) so
// handle+poll doesn't apply, but a cold restore can exceed Cloudflare's
- // 100s → 524 (or the 90s WakeSandbox cap → 502). Instead of restoring
- // on the connection, kick the wake to the background and return 503
- // "waking" + Retry-After; the SDK retries and the warm retry proxies
- // normally (the restore flips the DB status to running). Wake is deduped
- // across control planes via a Redis lock so we never double-restore.
- if isFilesPath(c) {
+ // 100s → 524 (or the 90s WakeSandbox cap → 502). For clients that opt in
+ // (X-OSB-Async-Wake — the newer SDK, which retries on 503), kick the wake
+ // to the background and return 503 "waking" + Retry-After; the warm retry
+ // proxies normally. Older SDKs don't send the header and don't retry, so
+ // they fall through to the inline synchronous wake below (their original
+ // behavior). Wake is deduped across control planes via a Redis lock so we
+ // never double-restore.
+ if isFilesPath(c) && wantsAsyncWake(c) {
p.startBackgroundWake(sandboxID)
c.Response().Header().Set("Retry-After", "1")
return c.JSON(http.StatusServiceUnavailable, map[string]any{
@@ -332,10 +334,18 @@ func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {
func isAsyncExecPath(c echo.Context) bool {
p := c.Request().URL.Path
m := c.Request().Method
- return (m == http.MethodPost && strings.HasSuffix(p, "/exec/run")) ||
+ return (m == http.MethodPost && strings.HasSuffix(p, "/exec/run-async")) ||
(m == http.MethodGet && strings.HasSuffix(p, "/result"))
}
+// wantsAsyncWake reports whether the client opted into the background-wake +
+// 503-retry flow for an otherwise-synchronous op (file ops). Newer SDKs send the
+// X-OSB-Async-Wake header and retry on 503 {waking}; older SDKs don't, so they
+// keep the inline synchronous wake below — preserving their original behavior.
+func wantsAsyncWake(c echo.Context) bool {
+ return c.Request().Header.Get("X-OSB-Async-Wake") == "1"
+}
+
// isFilesPath reports whether the request targets the filesystem API
// (read/write/list/mkdir/remove, including the signed download/upload variants
// that re-enter via the proxy). These are synchronous ops that tolerate a 503
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index eae267af..d6943463 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -285,6 +285,13 @@ type asyncExec struct {
createMs int64 // session create once the box was up
}
+// execRun is the synchronous one-shot exec endpoint (POST /exec/run). It holds
+// the connection for the command's duration and returns {exitCode,stdout,stderr}
+// directly. Kept unchanged for SDK versions that predate the async flow; newer
+// SDKs POST /exec/run-async instead (see execRunAsync). For timeout>30 it streams
+// keepalive whitespace so the edge doesn't 524 on a long command — the original
+// band-aid — but a cold-start wake is still held on the connection here, which is
+// exactly why the async path exists.
func (s *HTTPServer) execRun(c echo.Context) error {
id := c.Param("id")
@@ -296,11 +303,92 @@ func (s *HTTPServer) execRun(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
}
- // Async path: register a handle synchronously and return immediately, then
- // do the wake + session-create + command run in a background goroutine.
- // Because the connection is never held — not for the command, and crucially
- // not for a slow auto-wake/restore — the edge never 524s (nor 502s on the
- // CP's 60s response-header timeout). The caller polls GET /exec/:execId/result.
+ // For long-running commands (timeout > 30s), send response headers
+ // immediately and write periodic keepalive whitespace. This prevents
+ // Cloudflare (and other reverse proxies) from timing out:
+ // - 524 first-byte timeout (~100s): solved by sending headers early
+ // - Body idle timeout (~600s): solved by periodic space bytes
+ // JSON parsers ignore leading whitespace, so the final JSON body
+ // is parsed cleanly regardless of how many spaces precede it.
+ earlyFlush := req.Timeout > 30
+ var keepaliveDone chan struct{}
+ if earlyFlush {
+ c.Response().Header().Set("Content-Type", "application/json")
+ c.Response().WriteHeader(http.StatusOK)
+ flusher, _ := c.Response().Writer.(http.Flusher)
+ if flusher != nil {
+ flusher.Flush()
+ }
+
+ keepaliveDone = make(chan struct{})
+ go func() {
+ ticker := time.NewTicker(15 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ c.Response().Write([]byte(" "))
+ if flusher != nil {
+ flusher.Flush()
+ }
+ case <-keepaliveDone:
+ return
+ }
+ }
+ }()
+ }
+
+ var result *types.ProcessResult
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ result, err = s.manager.Exec(ctx, id, req)
+ return err
+ }
+
+ var execErr error
+ if s.router != nil {
+ execErr = s.router.Route(c.Request().Context(), id, "execRun", routeOp)
+ } else {
+ execErr = routeOp(c.Request().Context())
+ }
+
+ if keepaliveDone != nil {
+ close(keepaliveDone)
+ }
+
+ if execErr != nil {
+ if earlyFlush {
+ return json.NewEncoder(c.Response()).Encode(map[string]string{"error": execErr.Error()})
+ }
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": execErr.Error()})
+ }
+
+ if earlyFlush {
+ return json.NewEncoder(c.Response()).Encode(result)
+ }
+ return c.JSON(http.StatusOK, result)
+}
+
+// execRunAsync is the async exec endpoint (POST /exec/run-async). It registers a
+// handle synchronously and returns immediately, then does the wake +
+// session-create + command run in a background goroutine. Because the connection
+// is never held — not for the command, and crucially not for a slow
+// auto-wake/restore — the edge never 524s (nor 502s on the CP's 60s
+// response-header timeout). The caller polls GET /exec/:execId/result.
+func (s *HTTPServer) execRunAsync(c echo.Context) error {
+ id := c.Param("id")
+
+ var req types.ProcessConfig
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if req.Command == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
+ }
+
+ // Register a handle synchronously and return immediately, then do the wake +
+ // session-create + command run in a background goroutine.
if s.execSessionManager != nil {
execID := uuid.NewString()[:8]
ae := &asyncExec{state: asyncExecStarting, startedAt: time.Now()}
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index 7d3f2d01..1a1b1be2 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -85,7 +85,8 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
api.GET("/sandboxes/:id", s.getSandbox)
// Exec sessions (replaces old /commands)
- api.POST("/sandboxes/:id/exec/run", s.execRun) // static path before parameterized
+ api.POST("/sandboxes/:id/exec/run", s.execRun) // static path before parameterized (sync, legacy)
+ api.POST("/sandboxes/:id/exec/run-async", s.execRunAsync) // async handle + poll /result
api.POST("/sandboxes/:id/exec", s.createExecSession)
api.GET("/sandboxes/:id/exec", s.listExecSessions)
api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
diff --git a/scripts/524/confirm.sh b/scripts/524/confirm.sh
index 000701c9..598570c7 100755
--- a/scripts/524/confirm.sh
+++ b/scripts/524/confirm.sh
@@ -10,7 +10,9 @@ set -uo pipefail
: "${OSB_API_KEY:?set OSB_API_KEY}"
: "${OSB_BASE:?set OSB_BASE (e.g. https://app2.opensandbox.ai)}"
API="$OSB_BASE/api"
-H=(-H "X-API-Key: $OSB_API_KEY" -H "User-Agent: curl/8.0" -H "Content-Type: application/json")
+# X-OSB-Async-Wake opts into the 503-waking cold-start flow for file ops (the
+# newer SDK sends this; older SDKs get the inline synchronous wake instead).
+H=(-H "X-API-Key: $OSB_API_KEY" -H "User-Agent: curl/8.0" -H "Content-Type: application/json" -H "X-OSB-Async-Wake: 1")
PASS=0; FAIL=0
ok(){ echo " PASS: $1"; PASS=$((PASS+1)); }
no(){ echo " FAIL: $1"; FAIL=$((FAIL+1)); }
@@ -21,7 +23,7 @@ hibernate(){ curl -s "${H[@]}" -X POST "$API/sandboxes/$1/hibernate" >/dev/null
run_and_wait(){ # sid cmd -> "exit|stdout|post_secs"
local rj; rj=$(curl -s -w '\n%{time_total}' "${H[@]}" -X POST \
-d "$(python3 -c 'import json,sys;print(json.dumps({"cmd":"sh","args":["-c",sys.argv[1]]}))' "$2")" \
- "$API/sandboxes/$1/exec/run")
+ "$API/sandboxes/$1/exec/run-async")
local ps eid; ps=$(echo "$rj"|tail -1); eid=$(echo "$rj"|head -1|python3 -c 'import sys,json;print(json.load(sys.stdin).get("execId",""))')
local r; for _ in $(seq 1 300); do r=$(curl -s "${H[@]}" "$API/sandboxes/$1/exec/$eid/result")
[ "$(echo "$r"|python3 -c 'import sys,json;print(json.load(sys.stdin)["running"])')" = False ] && break; sleep 0.5; done
@@ -41,7 +43,7 @@ IFS='|' read -r ec so ps <<<"$(run_and_wait "$SID" 'echo e>&2; exit 7')"; [ "$ec
echo "=== exec/run: cold (hibernated) returns immediately ==="
hibernate "$SID"
-T=$(curl -s -o /tmp/c_run -w '%{time_total}' "${H[@]}" -X POST -d '{"cmd":"sh","args":["-c","echo woke"]}' "$API/sandboxes/$SID/exec/run")
+T=$(curl -s -o /tmp/c_run -w '%{time_total}' "${H[@]}" -X POST -d '{"cmd":"sh","args":["-c","echo woke"]}' "$API/sandboxes/$SID/exec/run-async")
echo " cold POST=${T}s"
python3 -c "import sys;sys.exit(0 if float('$T')<5 else 1)" && ok "cold exec POST <5s" || no "cold exec POST ${T}s"
@@ -59,7 +61,7 @@ for _ in $(seq 1 60); do B=$(curl -s -w '|%{http_code}' "${H[@]}" "$API/sandboxe
echo "=== snapshots: non-SSE build is async (building -> ready) ==="
TS=$(date +%s)
B=$(curl -s -o /tmp/c_s -w '%{time_total}' "${H[@]}" -X POST \
- -d "{\"name\":\"confirm-$TS\",\"image\":{\"base\":\"ubuntu\",\"steps\":[{\"type\":\"run\",\"args\":{\"commands\":[\"echo hi\"]}}]}}" "$API/snapshots")
+ -d "{\"name\":\"confirm-$TS\",\"image\":{\"base\":\"ubuntu\",\"steps\":[{\"type\":\"run\",\"args\":{\"commands\":[\"echo hi\"]}}]}}" "$API/snapshots?async=1")
echo " POST=${B}s status=$(python3 -c 'import json;print(json.load(open("/tmp/c_s")).get("status"))')"
python3 -c "import sys;sys.exit(0 if float('$B')<5 else 1)" && ok "snapshot POST <5s" || no "snapshot POST ${B}s"
for _ in $(seq 1 120); do ST=$(curl -s "${H[@]}" "$API/snapshots/confirm-$TS" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("status"))' 2>/dev/null)
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
index 6c86bb4b..a764b68a 100644
--- a/sdks/typescript/src/exec.ts
+++ b/sdks/typescript/src/exec.ts
@@ -347,7 +347,7 @@ export class Exec {
/**
* Run a command and wait for it to finish, returning its result.
*
- * Transparently async: POSTs to /exec/run (which returns a handle
+ * Transparently async: POSTs to /exec/run-async (which returns a handle
* immediately) then polls /exec/:execId/result until the command exits. Each
* HTTP request is sub-second, so there is no proxy 524 regardless of how long
* the command runs, and a dropped poll simply retries — the result persists
@@ -367,7 +367,7 @@ export class Exec {
if (opts.cwd) body.cwd = opts.cwd;
body.timeout = opts.timeout != null ? opts.timeout : 60;
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run`, {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run-async`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -380,7 +380,8 @@ export class Exec {
const handle = (await resp.json()) as ExecRunHandle;
- // Back-compat: an older (synchronous) origin returns the full result.
+ // Back-compat: a worker without the async endpoint (synchronous origin)
+ // returns the full result directly.
if (handle.execId == null && handle.exitCode != null) {
return {
exitCode: handle.exitCode,
diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.ts
index d92541d8..1be18e23 100644
--- a/sdks/typescript/src/filesystem.ts
+++ b/sdks/typescript/src/filesystem.ts
@@ -14,8 +14,14 @@ export class Filesystem {
) {}
private get headers(): Record<string, string> {
- if (this.token) return { "Authorization": `Bearer ${this.token}` };
- return this.apiKey ? { "X-API-Key": this.apiKey } : {};
+ // X-OSB-Async-Wake opts into the control plane's background-wake + 503
+ // {waking} flow on a cold sandbox (wfetch retries it), instead of the inline
+ // synchronous wake older SDKs get — which can hold the connection past the
+ // edge's ~100s and 524. Harmless when the box is already warm.
+ const h: Record<string, string> = { "X-OSB-Async-Wake": "1" };
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
+ else if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ return h;
}
// wfetch transparently rides out a cold-start wake. If the sandbox is