An open-source, faster Devin alternative
TypeScript
Default sandbox timeout to 0 (persistent, never hibernate) (#130)
Mohamed Habib901fe1cf894c
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.goindex 90a95b3d..857b67aa 100644--- a/cmd/oc/internal/commands/checkpoint.go+++ b/cmd/oc/internal/commands/checkpoint.go@@ -149,7 +149,7 @@ func init() {checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")checkpointCreateCmd.MarkFlagRequired("name")- checkpointSpawnCmd.Flags().Int("timeout", 300, "Timeout in seconds")+ checkpointSpawnCmd.Flags().Int("timeout", 0, "Idle timeout in seconds before auto-hibernate (0 = never hibernate)")checkpointCmd.AddCommand(checkpointCreateCmd)checkpointCmd.AddCommand(checkpointListCmd)diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.goindex 1e435001..3f53c42e 100644--- a/cmd/oc/internal/commands/sandbox.go+++ b/cmd/oc/internal/commands/sandbox.go@@ -224,7 +224,7 @@ var lsShortcut = &cobra.Command{func init() {// sandbox create flagsfor _, cmd := range []*cobra.Command{sandboxCreateCmd, createShortcut} {- cmd.Flags().Int("timeout", 300, "Timeout in seconds")+ cmd.Flags().Int("timeout", 0, "Idle timeout in seconds before auto-hibernate (0 = never hibernate)")cmd.Flags().Int("cpu", 0, "CPU count")cmd.Flags().Int("memory", 0, "Memory in MB")cmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")@@ -233,7 +233,7 @@ func init() {}// sandbox wake flags- sandboxWakeCmd.Flags().Int("timeout", 300, "Timeout in seconds after wake")+ sandboxWakeCmd.Flags().Int("timeout", 0, "Idle timeout in seconds after wake (0 = never hibernate)")sandboxCmd.AddCommand(sandboxCreateCmd)sandboxCmd.AddCommand(sandboxListCmd)diff --git a/docs/mint.json b/docs/mint.jsonindex 479bcab4..918a7f06 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -65,6 +65,7 @@"sandboxes/working-with-files","sandboxes/signed-urls","sandboxes/interactive-terminals",+ "sandboxes/timeout","sandboxes/checkpoints","sandboxes/templates","sandboxes/secrets",diff --git a/docs/sandboxes/timeout.mdx b/docs/sandboxes/timeout.mdxnew file mode 100644index 00000000..2d5c2677--- /dev/null+++ b/docs/sandboxes/timeout.mdx@@ -0,0 +1,133 @@+---+title: "Timeout & Hibernation"+description: "Control how long a sandbox stays alive when idle"+---++Sandboxes have a rolling **idle timeout** that determines when they auto-hibernate to save cost. The timeout is what you'd expect from a "laptop lid" — the sandbox sleeps when nothing is happening and wakes the moment you talk to it again.++## Default: persistent (no auto-hibernate)++By default the timeout is `0`, which means **never auto-hibernate**. The sandbox stays running until you explicitly kill or hibernate it.++<CodeGroup>++```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";++// No `timeout` — sandbox is persistent (stays alive until killed).+const sandbox = await Sandbox.create();+```++```python Python+from opencomputer import Sandbox++# No `timeout` — sandbox is persistent (stays alive until killed).+sandbox = await Sandbox.create()+```++```bash CLI+# --timeout defaults to 0 (never hibernate).+oc sandbox create+```++</CodeGroup>++<Note>+ Persistent sandboxes keep accruing compute cost for as long as they're running. If you only need the sandbox to respond to occasional requests, set a timeout so it hibernates between them — see below.+</Note>++## Setting a timeout++Pass `timeout` in seconds to have the sandbox auto-hibernate after N seconds of **idle** time. The timer resets on every operation — exec, file access, agent activity — so a busy sandbox never hits the timeout.++<CodeGroup>++```typescript TypeScript+// Auto-hibernate after 5 minutes of inactivity.+const sandbox = await Sandbox.create({ timeout: 300 });+```++```python Python+# Auto-hibernate after 5 minutes of inactivity.+sandbox = await Sandbox.create(timeout=300)+```++```bash CLI+oc sandbox create --timeout 300+```++</CodeGroup>++### Update on a running sandbox++You can change the timeout at any time:++<CodeGroup>++```typescript TypeScript+await sandbox.setTimeout(600); // 10 minutes+await sandbox.setTimeout(0); // make it persistent+```++```python Python+await sandbox.set_timeout(600)+await sandbox.set_timeout(0)+```++```bash CLI+oc sandbox set-timeout sb-abc123 600+oc sandbox set-timeout sb-abc123 0+```++</CodeGroup>++## What happens when the timeout expires++When an idle sandbox hits its timeout, the platform:++1. Snapshots the VM state (memory + disk) and stops the VM — no compute cost while hibernated.+2. Marks the sandbox `hibernated`. Its ID, files, and configuration are preserved.++You don't pay for CPU/memory while a sandbox is hibernated — only for the stored snapshot.++## Waking up++**Any operation from the SDK automatically wakes a hibernated sandbox.** You don't need to call `wake()` yourself — calling `sandbox.exec.run(...)`, reading a file, or any other operation transparently restores the VM and then performs the requested action.++<CodeGroup>++```typescript TypeScript+// Earlier: sandbox auto-hibernated after 5 minutes of idleness.+// Now, hours later — this call just works. The SDK wakes it first.+const result = await sandbox.exec.run("echo hello");+```++```python Python+# Same behavior in Python.+result = await sandbox.exec.run("echo hello")+```++</CodeGroup>++Wake is typically sub-second thanks to snapshot restore, with a cold-boot fallback if the snapshot isn't available. Once woken, the idle timer restarts with the sandbox's configured timeout.++<Note>+ You can still call `sandbox.wake()` explicitly if you want to pre-warm a sandbox before routing user traffic to it.+</Note>++## Choosing a timeout++| Use case | Suggested `timeout` |+| --- | --- |+| Always-on agent / bot that must respond instantly | `0` (persistent) |+| Interactive dev sandbox, keep for the session | `600`–`3600` (10 min – 1 hr) |+| Short-lived batch or test run | `60`–`300` (1–5 min) |+| One-off exec — kill it yourself when done | `0` + explicit `kill()` |++The tradeoff is latency vs cost: a lower timeout saves money but adds wake latency on the next request after idleness.++## See also++- [Lifecycle overview](/sandboxes/overview#lifecycle) — all sandbox states+- [Set timeout API](/api-reference/sandboxes/set-timeout)+- [Hibernate API](/api-reference/sandboxes/hibernate) / [Wake API](/api-reference/sandboxes/wake)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 84acd559..72a2da2c 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -163,11 +163,13 @@ func (s *Server) createSandbox(c echo.Context) error {})}- // Register with sandbox router for rolling timeout tracking+ // Register with sandbox router for rolling timeout tracking.+ // timeout == 0 means "persistent" (no auto-hibernate). Negative values are+ // normalized to 0 for safety.if s.router != nil {timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}@@ -769,9 +771,11 @@ func (s *Server) setTimeout(c echo.Context) error {})}- if req.Timeout <= 0 {+ // timeout == 0 means "persistent" (disable auto-hibernate). Negative values+ // are invalid.+ if req.Timeout < 0 {return c.JSON(http.StatusBadRequest, map[string]string{- "error": "timeout must be positive",+ "error": "timeout must be non-negative (0 disables auto-hibernate)",})}@@ -1182,11 +1186,12 @@ func (s *Server) wakeSandbox(c echo.Context) error {})}- // Register with sandbox router after explicit wake+ // Register with sandbox router after explicit wake.+ // timeout == 0 means "persistent" (no auto-hibernate).if s.router != nil {timeout := req.Timeout- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(id, time.Duration(timeout)*time.Second)}@@ -1270,10 +1275,6 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W// Issue fresh JWTorgID, _ := auth.GetOrgID(c)- timeout := req.Timeout- if timeout <= 0 {- timeout = 300- }var token stringif s.jwtIssuer != nil {t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, worker.ID, 24*time.Hour)@@ -1720,12 +1721,17 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st}}+ // Resolve timeout. With int-valued JSON fields we can't distinguish "not sent"+ // from "explicitly zero", so treat req.Timeout as authoritative. Fall back to+ // the checkpoint's original timeout only when req.Timeout is negative (which is+ // itself invalid, but could occur historically). timeout == 0 is valid and means+ // "persistent / never auto-hibernate".timeout := req.Timeout- if timeout <= 0 {+ if timeout < 0 {timeout = originalCfg.Timeout}- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}// Unified async fork: return immediately, boot VM in background.diff --git a/internal/qemu/docs_compliance_test.go b/internal/qemu/docs_compliance_test.goindex 9aa6f8d3..12e5f62f 100644--- a/internal/qemu/docs_compliance_test.go+++ b/internal/qemu/docs_compliance_test.go@@ -274,7 +274,7 @@ func TestDocumentedSandboxResponseFields(t *testing.T) {// TestDocumentedDefaultValues verifies that QEMU manager defaults match docs.//-// Docs say: cpuCount=1, memoryMB=256, timeout=300, port=80+// Docs say: cpuCount=1, memoryMB=256, timeout=0 (persistent), port=80func TestDocumentedDefaultValues(t *testing.T) {// NewManager applies defaults to zero-valued Config fields.// We simulate that logic here since NewManager needs real dirs.diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 27750472..d51f4138 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -145,9 +145,10 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqsb, err := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)if err == nil {if s.router != nil {+ // timeout == 0 means "persistent" (no auto-hibernate).timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}@@ -166,9 +167,10 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqsb, err = s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)if err == nil {if s.router != nil {+ // timeout == 0 means "persistent" (no auto-hibernate).timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}@@ -200,11 +202,12 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqreturn nil, fmt.Errorf("failed to create sandbox: %w", err)}- // Register with sandbox router for rolling timeout tracking+ // Register with sandbox router for rolling timeout tracking.+ // timeout == 0 means "persistent" (no auto-hibernate).if s.router != nil {timeout := cfg.Timeout- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}@@ -573,11 +576,12 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequestreturn nil, fmt.Errorf("failed to wake sandbox: %w", err)}- // Register with sandbox router after explicit wake+ // Register with sandbox router after explicit wake.+ // timeout == 0 means "persistent" (no auto-hibernate).if s.router != nil {timeout := int(req.Timeout)- if timeout <= 0 {- timeout = 300+ if timeout < 0 {+ timeout = 0}s.router.Register(sb.ID, time.Duration(timeout)*time.Second)}diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex 6983f05a..0888944a 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -34,7 +34,7 @@ class Sandbox:async def create(cls,template: str = "base",- timeout: int = 300,+ timeout: int = 0,api_key: str | None = None,api_url: str | None = None,envs: dict[str, str] | None = None,@@ -49,7 +49,7 @@ class Sandbox:Args:template: Template to use (default "base").- timeout: Sandbox timeout in seconds (default 300).+ timeout: Idle timeout in seconds. 0 = persistent, never auto-hibernates (default).api_key: API key (or OPENCOMPUTER_API_KEY env var).api_url: API URL (or OPENCOMPUTER_API_URL env var).envs: Environment variables to inject. Overrides store secrets.@@ -340,7 +340,7 @@ class Sandbox:async def create_from_checkpoint(cls,checkpoint_id: str,- timeout: int = 300,+ timeout: int = 0,api_key: str | None = None,api_url: str | None = None,envs: dict[str, str] | None = None,@@ -350,7 +350,7 @@ class Sandbox:Args:checkpoint_id: UUID of the checkpoint to fork from.- timeout: Sandbox timeout in seconds (default 300).+ timeout: Idle timeout in seconds. 0 = persistent, never auto-hibernates (default).api_key: API key (or OPENCOMPUTER_API_KEY env var).api_url: API URL (or OPENCOMPUTER_API_URL env var).envs: Environment variables to override on the fork.diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex d9c49838..17fc2f8b 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -13,6 +13,10 @@ function resolveApiUrl(url: string): string {export interface SandboxOpts {template?: string;+ /**+ * Idle timeout in seconds after which the sandbox auto-hibernates.+ * Default: `0` (persistent — never auto-hibernate).+ */timeout?: number;apiKey?: string;apiUrl?: string;@@ -142,7 +146,8 @@ export class Sandbox {const body: Record<string, unknown> = {templateID: opts.template ?? "base",- timeout: opts.timeout ?? 300,+ // Default to 0 (persistent). Callers who want auto-hibernate must opt in.+ timeout: opts.timeout ?? 0,};if (opts.envs) body.envs = opts.envs;if (opts.metadata) body.metadata = opts.metadata;@@ -251,7 +256,8 @@ export class Sandbox {"Content-Type": "application/json",...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),},- body: JSON.stringify({ timeout: opts.timeout ?? 300 }),+ // Default to 0 (persistent) — matches create() default.+ body: JSON.stringify({ timeout: opts.timeout ?? 0 }),});if (!resp.ok) {