Skip to content

An open-source, faster Devin alternative

TypeScript

update sdks,cli,docs

Brian Reardon86b3ca435450
diff --git a/cmd/oc/internal/commands/scaling.go b/cmd/oc/internal/commands/scaling.go
new file mode 100644
index 00000000..bd4024e7
--- /dev/null
+++ b/cmd/oc/internal/commands/scaling.go
@@ -0,0 +1,206 @@
+package commands
+
+import (
+ "fmt"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+var sandboxScaleCmd = &cobra.Command{
+ Use: "scale <sandbox-id> <memory-mb>",
+ Short: "Manually resize a sandbox",
+ Long: `Manually resize a sandbox to a specific memory tier. CPU follows memory
+per the platform's tier table (e.g. 8 GB → 4 vCPU). Allowed tiers:
+1024, 4096, 8192, 16384, 32768, 65536 MB.
+
+A manual scale disables autoscale on this sandbox as a side effect; re-
+enable with 'oc sandbox autoscale --on' if you want it back.
+
+Errors:
+ scaling_locked Sandbox has a scaling lock — unlock first.
+ 402 Payment... Requested size exceeds your plan cap.`,
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var memoryMB int
+ if _, err := fmt.Sscanf(args[1], "%d", &memoryMB); err != nil || memoryMB <= 0 {
+ return fmt.Errorf("invalid memory-mb: %s", args[1])
+ }
+
+ var resp struct {
+ SandboxID string `json:"sandboxID"`
+ MemoryMB int `json:"memoryMB"`
+ CPUPercent int `json:"cpuPercent"`
+ }
+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/scale", map[string]int{"memoryMB": memoryMB}, &resp); err != nil {
+ return err
+ }
+
+ printer.Print(resp, func() {
+ fmt.Printf("Scaled %s to %dMB / %d%% CPU\n", resp.SandboxID, resp.MemoryMB, resp.CPUPercent)
+ })
+ return nil
+ },
+}
+
+var sandboxAutoscaleCmd = &cobra.Command{
+ Use: "autoscale <sandbox-id>",
+ Short: "Configure or inspect per-sandbox autoscale",
+ Long: `Configure or inspect per-sandbox autoscale.
+
+Run with no flags to print the current configuration.
+Use --on with --min/--max to enable; --off to disable.
+
+When enabled, the platform resizes the sandbox between min and max based
+on observed memory pressure: scale up fast on a 1-min spike (>75%), scale
+down only after sustained idle (1m + 5m + 15m all below 25%, 5-min
+cooldown).
+
+Errors:
+ scaling_locked Sandbox has a scaling lock — unlock first to enable.
+ 402 Payment... --max exceeds your plan cap.`,
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ on, _ := cmd.Flags().GetBool("on")
+ off, _ := cmd.Flags().GetBool("off")
+ minMB, _ := cmd.Flags().GetInt("min")
+ maxMB, _ := cmd.Flags().GetInt("max")
+
+ // No flags → status
+ if !on && !off && minMB == 0 && maxMB == 0 {
+ var status struct {
+ SandboxID string `json:"sandboxID"`
+ Enabled bool `json:"enabled"`
+ MinMemoryMB int `json:"minMemoryMB"`
+ MaxMemoryMB int `json:"maxMemoryMB"`
+ }
+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", &status); err != nil {
+ return err
+ }
+ printer.Print(status, func() {
+ if status.Enabled {
+ fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", status.SandboxID, status.MinMemoryMB, status.MaxMemoryMB)
+ } else {
+ fmt.Printf("Autoscale disabled for %s\n", status.SandboxID)
+ }
+ })
+ return nil
+ }
+
+ if on && off {
+ return fmt.Errorf("--on and --off are mutually exclusive")
+ }
+
+ body := map[string]interface{}{"enabled": on}
+ if on {
+ if minMB == 0 || maxMB == 0 {
+ return fmt.Errorf("--on requires both --min and --max")
+ }
+ body["minMemoryMB"] = minMB
+ body["maxMemoryMB"] = maxMB
+ }
+
+ var resp struct {
+ SandboxID string `json:"sandboxID"`
+ Enabled bool `json:"enabled"`
+ MinMemoryMB int `json:"minMemoryMB"`
+ MaxMemoryMB int `json:"maxMemoryMB"`
+ }
+ if err := c.PutJSON(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", body, &resp); err != nil {
+ return err
+ }
+ printer.Print(resp, func() {
+ if resp.Enabled {
+ fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", resp.SandboxID, resp.MinMemoryMB, resp.MaxMemoryMB)
+ } else {
+ fmt.Printf("Autoscale disabled for %s\n", resp.SandboxID)
+ }
+ })
+ return nil
+ },
+}
+
+var sandboxLockCmd = &cobra.Command{
+ Use: "lock <sandbox-id>",
+ Short: "Pin a sandbox at its current size (block scaling)",
+ Long: `Lock the sandbox against any size change. While locked, both 'scale'
+and 'autoscale --on' are rejected with a scaling_locked error, and the
+platform autoscaler skips the sandbox entirely.
+
+Locking ALSO disables autoscale (single-knob: "I don't want this scaling,
+period"). Unlocking does NOT re-enable autoscale; run 'autoscale --on'
+explicitly if you want it back.`,
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return setScalingLock(cmd, args[0], true)
+ },
+}
+
+var sandboxUnlockCmd = &cobra.Command{
+ Use: "unlock <sandbox-id>",
+ Short: "Allow scaling on a sandbox again (clear the lock)",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return setScalingLock(cmd, args[0], false)
+ },
+}
+
+var sandboxLockStatusCmd = &cobra.Command{
+ Use: "lock-status <sandbox-id>",
+ Short: "Show the scaling-lock state of a sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ var resp struct {
+ SandboxID string `json:"sandboxID"`
+ Locked bool `json:"locked"`
+ }
+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/scaling-lock", &resp); err != nil {
+ return err
+ }
+ printer.Print(resp, func() {
+ if resp.Locked {
+ fmt.Printf("Sandbox %s is LOCKED (no scaling)\n", resp.SandboxID)
+ } else {
+ fmt.Printf("Sandbox %s is unlocked\n", resp.SandboxID)
+ }
+ })
+ return nil
+ },
+}
+
+func setScalingLock(cmd *cobra.Command, sandboxID string, locked bool) error {
+ c := client.FromContext(cmd.Context())
+ var resp struct {
+ SandboxID string `json:"sandboxID"`
+ Locked bool `json:"locked"`
+ }
+ body := map[string]bool{"locked": locked}
+ if err := c.PutJSON(cmd.Context(), "/sandboxes/"+sandboxID+"/scaling-lock", body, &resp); err != nil {
+ return err
+ }
+ printer.Print(resp, func() {
+ if resp.Locked {
+ fmt.Printf("Sandbox %s locked (scaling disabled)\n", resp.SandboxID)
+ } else {
+ fmt.Printf("Sandbox %s unlocked\n", resp.SandboxID)
+ }
+ })
+ return nil
+}
+
+func init() {
+ sandboxAutoscaleCmd.Flags().Bool("on", false, "Enable autoscale (requires --min and --max)")
+ sandboxAutoscaleCmd.Flags().Bool("off", false, "Disable autoscale")
+ sandboxAutoscaleCmd.Flags().Int("min", 0, "Minimum memory tier in MB (allowed: 1024, 4096, 8192, 16384, 32768, 65536)")
+ sandboxAutoscaleCmd.Flags().Int("max", 0, "Maximum memory tier in MB (allowed: 1024, 4096, 8192, 16384, 32768, 65536)")
+
+ sandboxCmd.AddCommand(sandboxScaleCmd)
+ sandboxCmd.AddCommand(sandboxAutoscaleCmd)
+ sandboxCmd.AddCommand(sandboxLockCmd)
+ sandboxCmd.AddCommand(sandboxUnlockCmd)
+ sandboxCmd.AddCommand(sandboxLockStatusCmd)
+}
diff --git a/docs/docs.json b/docs/docs.json
index 2b8bbf5c..5012e24b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -122,6 +122,7 @@
"pages": [
"reference/typescript-sdk/overview",
"reference/typescript-sdk/sandbox",
+ "reference/typescript-sdk/scaling",
"reference/typescript-sdk/exec",
"reference/typescript-sdk/filesystem",
"reference/typescript-sdk/pty",
@@ -135,6 +136,7 @@
"pages": [
"reference/python-sdk/overview",
"reference/python-sdk/sandbox",
+ "reference/python-sdk/scaling",
"reference/python-sdk/exec",
"reference/python-sdk/filesystem",
"reference/python-sdk/pty",
@@ -149,6 +151,7 @@
"reference/cli/overview",
"reference/cli/agent",
"reference/cli/sandbox",
+ "reference/cli/scaling",
"reference/cli/exec",
"reference/cli/shell",
"reference/cli/checkpoint",
diff --git a/docs/reference/cli/sandbox.mdx b/docs/reference/cli/sandbox.mdx
index 49985521..c413f4af 100644
--- a/docs/reference/cli/sandbox.mdx
+++ b/docs/reference/cli/sandbox.mdx
@@ -87,3 +87,7 @@ Update the idle timeout for a running sandbox. [HTTP API →](/api-reference/san
```bash
oc sandbox set-timeout sb-abc123 600
```
+
+---
+
+For commands that resize a sandbox or freeze its size — `scale`, `autoscale`, `lock`, `unlock`, `lock-status` — see [Scaling](/reference/cli/scaling).
diff --git a/docs/reference/cli/scaling.mdx b/docs/reference/cli/scaling.mdx
new file mode 100644
index 00000000..4a6b200d
--- /dev/null
+++ b/docs/reference/cli/scaling.mdx
@@ -0,0 +1,121 @@
+---
+title: "oc sandbox scaling"
+description: "Resize sandboxes, configure autoscale, and manage scaling locks from the CLI"
+---
+
+The CLI groups three related actions for sizing a sandbox:
+
+| Command | What it does |
+| --- | --- |
+| [`oc sandbox autoscale`](#oc-sandbox-autoscale-id) | Turn the platform autoscaler on/off and inspect its config |
+| [`oc sandbox scale`](#oc-sandbox-scale-id-memory-mb) | Manually resize once |
+| [`oc sandbox lock`](#oc-sandbox-lock-id) / [`unlock`](#oc-sandbox-unlock-id) / [`lock-status`](#oc-sandbox-lock-status-id) | Freeze or unfreeze the current size |
+
+Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU); you don't pick CPU separately.
+
+For the underlying concepts and how these three modes interact, see the [Elasticity](/sandboxes/elasticity) guide.
+
+---
+
+## `oc sandbox autoscale <id>`
+
+Configure or inspect per-sandbox autoscale. [HTTP API →](/api-reference/sandboxes/autoscale)
+
+Run with no flags to print the current configuration:
+
+```bash
+oc sandbox autoscale sb-abc123
+# Autoscale enabled for sb-abc123 (1024–16384 MB)
+```
+
+Enable with bounds:
+
+```bash
+oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384
+```
+
+Disable:
+
+```bash
+oc sandbox autoscale sb-abc123 --off
+```
+
+When enabled, the platform watches memory pressure and resizes the sandbox between `--min` and `--max`:
+
+- **Scale up** on a single 1-min sample above 75 % memory utilization. Cooldown 60 s between up-scales.
+- **Scale down** only when the 1-min, 5-min, AND 15-min averages all sit below 25 %. Cooldown 5 min between down-scales.
+
+The asymmetry is deliberate: rapid response when the user notices lag, conservative shrink after sustained idle.
+
+**Flags**
+
+| Flag | Description |
+| --- | --- |
+| `--on` | Enable autoscale (requires `--min` and `--max`). |
+| `--off` | Disable autoscale. Mutually exclusive with `--on`. |
+| `--min N` | Minimum memory tier in MB. Must be an allowed tier. |
+| `--max N` | Maximum memory tier in MB. Must be an allowed tier and ≥ `--min`. |
+
+**Errors**
+
+- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.
+- `402 Payment Required` — `--max` exceeds your plan cap.
+
+---
+
+## `oc sandbox scale <id> <memory-mb>`
+
+Manually resize a sandbox to a specific memory tier. [HTTP API →](/api-reference/sandboxes/scale)
+
+```bash
+oc sandbox scale sb-abc123 8192
+# Scaled sb-abc123 to 8192MB / 400% CPU
+```
+
+A manual scale **disables autoscale** on this sandbox as a side effect — explicit intent overrides the loop. Re-enable with `oc sandbox autoscale --on` if you want size to track load again.
+
+**Errors**
+
+- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.
+- `402 Payment Required` — requested size exceeds your plan cap.
+
+---
+
+## `oc sandbox lock <id>`
+
+Pin a sandbox at its current size. [HTTP API →](/api-reference/sandboxes/scaling-lock)
+
+```bash
+oc sandbox lock sb-abc123
+# Sandbox sb-abc123 locked (scaling disabled)
+```
+
+While locked:
+
+- `oc sandbox scale` is rejected with `scaling_locked`.
+- `oc sandbox autoscale --on` is rejected with `scaling_locked`.
+- The platform autoscaler skips the sandbox entirely.
+
+Locking **also** disables autoscale (single knob — "I don't want this scaling, period"). Unlocking does NOT re-enable autoscale; run `oc sandbox autoscale --on` explicitly if you want it back.
+
+---
+
+## `oc sandbox unlock <id>`
+
+Clear the scaling lock.
+
+```bash
+oc sandbox unlock sb-abc123
+# Sandbox sb-abc123 unlocked
+```
+
+---
+
+## `oc sandbox lock-status <id>`
+
+Print the current scaling-lock state.
+
+```bash
+oc sandbox lock-status sb-abc123
+# Sandbox sb-abc123 is unlocked
+```
diff --git a/docs/reference/python-sdk/scaling.mdx b/docs/reference/python-sdk/scaling.mdx
new file mode 100644
index 00000000..214f16c9
--- /dev/null
+++ b/docs/reference/python-sdk/scaling.mdx
@@ -0,0 +1,171 @@
+---
+title: "Scaling"
+description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."
+---
+
+OpenComputer sandboxes can change size at runtime. There are three knobs:
+
+| What you want | Use |
+| --- | --- |
+| Resize once, predictably | [`scale()`](#sandbox-scale-memory-mb) |
+| Track memory pressure automatically | [`set_autoscale()`](#sandbox-set-autoscale) |
+| Freeze the current size | [`set_scaling_lock()`](#sandbox-set-scaling-lock-locked) |
+
+Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU). You don't pick CPU separately.
+
+## How the three interact
+
+- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable with `set_autoscale(enabled=True, ...)` after if you want.
+- **Setting a scaling lock** disables autoscale at the same time (single knob: "I don't want this scaling, period"). While locked, both `scale()` and `set_autoscale(enabled=True)` raise `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.
+- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap raise `PlanLimitError`.
+
+---
+
+## `sandbox.scale(memory_mb)`
+
+Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)
+
+<ParamField body="memory_mb" type="int" required>
+ Target memory tier in MB. Must be one of the allowed tiers.
+</ParamField>
+
+**Returns:** `dict` with `sandboxID`, `memoryMB`, `cpuPercent`.
+
+**Raises:**
+
+- `ScalingLockedError` — sandbox has a scaling lock active.
+- `PlanLimitError` — `memory_mb` exceeds the org's plan cap.
+
+```python
+from opencomputer import Sandbox, ScalingLockedError, PlanLimitError
+
+sandbox = await Sandbox.connect("sb-abc123")
+
+try:
+ result = await sandbox.scale(memory_mb=8192)
+ print(f"scaled to {result['memoryMB']}MB / {result['cpuPercent']}% CPU")
+except ScalingLockedError:
+ print("sandbox is locked — unlock to scale")
+except PlanLimitError:
+ print("upgrade required for larger instances")
+```
+
+---
+
+## `sandbox.set_autoscale(enabled, *, min_memory_mb=None, max_memory_mb=None)`
+
+Enable or disable per-sandbox autoscale.
+
+<ParamField body="enabled" type="bool" required>
+ Whether autoscale should be active.
+</ParamField>
+
+<ParamField body="min_memory_mb" type="int">
+ Lower bound when `enabled=True`. Must be an allowed tier.
+</ParamField>
+
+<ParamField body="max_memory_mb" type="int">
+ Upper bound when `enabled=True`. Must be an allowed tier and ≥ `min_memory_mb`.
+</ParamField>
+
+**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.
+
+**Raises:**
+
+- `ScalingLockedError` — sandbox has a scaling lock active.
+- `PlanLimitError` — `max_memory_mb` exceeds the org's plan cap.
+
+When `enabled=True`, the platform watches the sandbox's memory pressure and resizes it within the bounds:
+
+- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.
+- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.
+
+The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.
+
+```python
+await sandbox.set_autoscale(
+ enabled=True,
+ min_memory_mb=1024,
+ max_memory_mb=16384,
+)
+```
+
+To turn off:
+
+```python
+await sandbox.set_autoscale(enabled=False)
+```
+
+---
+
+## `sandbox.get_autoscale()`
+
+Get the current autoscale configuration.
+
+**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.
+
+```python
+cfg = await sandbox.get_autoscale()
+if cfg["enabled"]:
+ print(f"autoscale {cfg['minMemoryMB']}–{cfg['maxMemoryMB']} MB")
+```
+
+---
+
+## `sandbox.set_scaling_lock(locked)`
+
+Lock or unlock the sandbox's resources against any size change.
+
+<ParamField body="locked" type="bool" required>
+ `True` to freeze, `False` to allow scaling again.
+</ParamField>
+
+**Returns:** `dict` with `sandboxID`, `locked`.
+
+While locked:
+
+- `scale()` raises `ScalingLockedError`.
+- `set_autoscale(enabled=True)` raises `ScalingLockedError`.
+- The platform autoscaler skips this sandbox entirely.
+
+Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `set_autoscale(enabled=True, ...)` explicitly if you want it back.
+
+```python
+# Pin a sandbox at its current size during a critical workload
+await sandbox.set_scaling_lock(True)
+
+# ...
+
+# Allow scaling again after
+await sandbox.set_scaling_lock(False)
+```
+
+---
+
+## `sandbox.get_scaling_lock()`
+
+Get the current scaling-lock state.
+
+**Returns:** `dict` with `sandboxID`, `locked`.
+
+---
+
+## Errors
+
+### `ScalingLockedError`
+
+Raised when the sandbox has a scaling lock active. Has a class attribute `code = "scaling_locked"` for parity with the HTTP API's error code.
+
+```python
+from opencomputer import ScalingLockedError
+
+try:
+ await sandbox.scale(memory_mb=8192)
+except ScalingLockedError:
+ # unlock first, or surface to user
+ ...
+```
+
+### `PlanLimitError`
+
+Raised when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.
diff --git a/docs/reference/typescript-sdk/scaling.mdx b/docs/reference/typescript-sdk/scaling.mdx
new file mode 100644
index 00000000..4ca44ae5
--- /dev/null
+++ b/docs/reference/typescript-sdk/scaling.mdx
@@ -0,0 +1,179 @@
+---
+title: "Scaling"
+description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."
+---
+
+OpenComputer sandboxes can change size at runtime. There are three knobs:
+
+| What you want | Use |
+| --- | --- |
+| Resize once, predictably | [`scale()`](#sandbox-scale-opts) |
+| Track memory pressure automatically | [`setAutoscale()`](#sandbox-setautoscale-opts) |
+| Freeze the current size | [`setScalingLock()`](#sandbox-setscalinglock-locked) |
+
+Memory tiers are fixed: `1024`, `4096`, `8192`, `16384`, `32768`, `65536` MB. CPU follows memory per the platform's tier table (e.g. 8 GB → 4 vCPU). You don't pick CPU separately.
+
+## How the three interact
+
+- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable autoscale with `setAutoscale({ enabled: true, ... })` after if you want.
+- **Setting a scaling lock** disables autoscale at the same time (single-knob: "I don't want this scaling, period"). While locked, both `scale()` and `setAutoscale({ enabled: true })` reject with `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.
+- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap throw `PlanLimitError`.
+
+---
+
+## `sandbox.scale(opts)`
+
+Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)
+
+<ParamField body="memoryMB" type="number" required>
+ Target memory tier in MB. Must be one of the allowed tiers.
+</ParamField>
+
+**Returns:** `Promise<{ sandboxID: string; memoryMB: number; cpuPercent: number }>`
+
+**Throws:**
+
+- `ScalingLockedError` — sandbox has a scaling lock active.
+- `PlanLimitError` — `memoryMB` exceeds the org's plan cap.
+
+```typescript
+import { Sandbox, ScalingLockedError, PlanLimitError } from "@opencomputer/sdk";
+
+const sandbox = await Sandbox.connect("sb-abc123");
+
+try {
+ const result = await sandbox.scale({ memoryMB: 8192 });
+ console.log(`scaled to ${result.memoryMB}MB / ${result.cpuPercent}% CPU`);
+} catch (err) {
+ if (err instanceof ScalingLockedError) {
+ console.warn("sandbox is locked — unlock to scale");
+ } else if (err instanceof PlanLimitError) {
+ console.warn("upgrade required for larger instances");
+ } else {
+ throw err;
+ }
+}
+```
+
+---
+
+## `sandbox.setAutoscale(opts)`
+
+Enable or disable per-sandbox autoscale.
+
+<ParamField body="enabled" type="boolean" required>
+ Whether autoscale should be active.
+</ParamField>
+
+<ParamField body="minMemoryMB" type="number">
+ Lower bound when `enabled=true`. Must be an allowed tier.
+</ParamField>
+
+<ParamField body="maxMemoryMB" type="number">
+ Upper bound when `enabled=true`. Must be an allowed tier and ≥ `minMemoryMB`.
+</ParamField>
+
+**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`
+
+**Throws:**
+
+- `ScalingLockedError` — sandbox has a scaling lock active.
+- `PlanLimitError` — `maxMemoryMB` exceeds the org's plan cap.
+
+When `enabled=true`, the platform watches the sandbox's memory pressure and resizes it within the bounds:
+
+- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.
+- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.
+
+The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.
+
+```typescript
+await sandbox.setAutoscale({
+ enabled: true,
+ minMemoryMB: 1024,
+ maxMemoryMB: 16384,
+});
+```
+
+To turn off:
+
+```typescript
+await sandbox.setAutoscale({ enabled: false });
+```
+
+---
+
+## `sandbox.getAutoscale()`
+
+Get the current autoscale configuration.
+
+**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`
+
+```typescript
+const cfg = await sandbox.getAutoscale();
+if (cfg.enabled) {
+ console.log(`autoscale ${cfg.minMemoryMB}–${cfg.maxMemoryMB} MB`);
+}
+```
+
+---
+
+## `sandbox.setScalingLock(locked)`
+
+Lock or unlock the sandbox's resources against any size change.
+
+<ParamField body="locked" type="boolean" required>
+ `true` to freeze, `false` to allow scaling again.
+</ParamField>
+
+**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`
+
+While locked:
+
+- `scale()` rejects with `ScalingLockedError`.
+- `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.
+- The platform autoscaler skips this sandbox entirely.
+
+Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `setAutoscale({ enabled: true, ... })` explicitly if you want it back.
+
+```typescript
+// Pin a sandbox at its current size during a critical workload
+await sandbox.setScalingLock(true);
+
+// ...
+
+// Allow scaling again after
+await sandbox.setScalingLock(false);
+```
+
+---
+
+## `sandbox.getScalingLock()`
+
+Get the current scaling-lock state.
+
+**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`
+
+---
+
+## Errors
+
+### `ScalingLockedError`
+
+Thrown when the sandbox has a scaling lock active. Has a `code` property of `"scaling_locked"` for parity with the HTTP API's error code.
+
+```typescript
+import { ScalingLockedError } from "@opencomputer/sdk";
+
+try {
+ await sandbox.scale({ memoryMB: 8192 });
+} catch (err) {
+ if (err instanceof ScalingLockedError) {
+ // unlock first, or surface to user
+ }
+}
+```
+
+### `PlanLimitError`
+
+Thrown when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.
diff --git a/docs/sandboxes/elasticity.mdx b/docs/sandboxes/elasticity.mdx
index 59995793..5a1333c5 100644
--- a/docs/sandboxes/elasticity.mdx
+++ b/docs/sandboxes/elasticity.mdx
@@ -1,15 +1,11 @@
---
title: "Elasticity"
-description: "Dynamically scale sandbox memory and CPU — manually, automatically, or via in-VM API"
+description: "Dynamically scale sandbox memory and CPU — automatically, manually, or via the in-VM API"
---
-A sandbox's memory and CPU can be resized at runtime. There are three ways to do it:
+A sandbox's memory and CPU can be resized at runtime. The platform's recommended path is **Autoscaling** — opt the sandbox in once and we resize it for you based on observed memory pressure. Lower-level controls are also available if you want to drive sizing yourself or freeze it.
-- **Inside the VM** — `POST http://169.254.169.254/v1/scale` lets code in the sandbox scale itself. Useful for workload-aware scripts (e.g. scale up before a build).
-- **From the control plane** — `POST /api/sandboxes/:id/scale` lets your application or a human operator resize externally.
-- **Automatically** — opt a sandbox into the per-sandbox autoscaler with `PUT /api/sandboxes/:id/autoscale` and the platform handles up/down based on observed memory pressure.
-
-CPU scales proportionally to memory in all three modes (1 vCPU per ~4 GB up to 16 GB / 4 vCPU). The permissible memory sizes are:
+CPU scales proportionally to memory in all modes (1 vCPU per ~4 GB up to 16 GB / 4 vCPU). The permissible memory tiers are:
| Memory | vCPU |
| --- | --- |
@@ -18,11 +14,135 @@ CPU scales proportionally to memory in all three modes (1 vCPU per ~4 GB up to 1
| 8 GB | 2 |
| 16 GB | 4 |
-If you want a sandbox to **stay at a fixed size**, see [Locking Resources](#locking-resources) below.
+If you want a sandbox to **stay at a fixed size**, see [Locking Resources](#locking-resources).
+
+## Autoscaling
+
+Opt a sandbox into the per-sandbox autoscaler and the platform resizes it for you based on observed memory pressure. Autoscale is **opt-in per sandbox** and **disabled by default**.
+
+This is the recommended way to size a sandbox: turn it on once with bounds you're comfortable with, then leave it. Manual `scale` and the in-VM API are escape hatches for cases where the autoscaler isn't a good fit (e.g. you want a hard guarantee for a benchmark, or you're scripting your own logic).
+
+### Enable
+
+<CodeGroup>
+```typescript TypeScript
+await sandbox.setAutoscale({
+ enabled: true,
+ minMemoryMB: 1024,
+ maxMemoryMB: 16384,
+});
+```
+
+```python Python
+await sandbox.set_autoscale(
+ enabled=True,
+ min_memory_mb=1024,
+ max_memory_mb=16384,
+)
+```
+
+```bash CLI
+oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384
+```
+
+```bash HTTP
+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"enabled": true, "minMemoryMB": 1024, "maxMemoryMB": 16384}'
+```
+</CodeGroup>
+
+`minMemoryMB` and `maxMemoryMB` must be values from the tier table above. The autoscaler keeps the sandbox between these bounds, in tier steps.
+
+### Behavior
+
+- **Scale up**: when the sandbox's 1-minute average memory utilization exceeds 75 %, jump to the next tier. 60-second cooldown between up-events.
+- **Scale down**: when **all** of the 1-min, 5-min, and 15-min utilization averages stay below 25 %, drop one tier. 5-minute cooldown between down-events. Down requires at least 15 minutes of low-utilization data, so a brief idle pause won't shrink you.
+- **Manual override**: any explicit `scale` call disables autoscale on that sandbox. Re-enable explicitly via `setAutoscale({ enabled: true, ... })` (or the equivalent in any SDK) if you want it back.
+
+### Disable
+
+<CodeGroup>
+```typescript TypeScript
+await sandbox.setAutoscale({ enabled: false });
+```
+
+```python Python
+await sandbox.set_autoscale(enabled=False)
+```
+
+```bash CLI
+oc sandbox autoscale sb-abc123 --off
+```
+
+```bash HTTP
+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
+ -H "X-API-Key: $API_KEY" \
+ -d '{"enabled": false}'
+```
+</CodeGroup>
+
+### Inspect
+
+<CodeGroup>
+```typescript TypeScript
+const cfg = await sandbox.getAutoscale();
+// { sandboxID: "sb-...", enabled: true, minMemoryMB: 1024, maxMemoryMB: 16384 }
+```
+
+```python Python
+cfg = await sandbox.get_autoscale()
+# {"sandboxID": "sb-...", "enabled": True, "minMemoryMB": 1024, "maxMemoryMB": 16384}
+```
+
+```bash CLI
+oc sandbox autoscale sb-abc123
+# Autoscale enabled for sb-abc123 (1024–16384 MB)
+```
+
+```bash HTTP
+curl -sf "$API/api/sandboxes/$SANDBOX_ID/autoscale" -H "X-API-Key: $API_KEY"
+# {"sandboxID":"sb-...","enabled":true,"minMemoryMB":1024,"maxMemoryMB":16384}
+```
+</CodeGroup>
+
+## Manual Scaling (Control Plane)
+
+When you want to resize once — predictable size for a benchmark, a one-off scale-up before a known-heavy task, an operator response to an alert — call `scale` from your application or operator tooling:
+
+<CodeGroup>
+```typescript TypeScript
+await sandbox.scale({ memoryMB: 4096 });
+```
+
+```python Python
+await sandbox.scale(memory_mb=4096)
+```
+
+```bash CLI
+oc sandbox scale sb-abc123 4096
+```
+
+```bash HTTP
+curl -sf -X POST "$API/api/sandboxes/$SANDBOX_ID/scale" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"memoryMB": 4096}'
+```
+</CodeGroup>
+
+A manual scale **disables autoscale** on the sandbox — explicit user intent overrides the loop. Re-enable it later if you want size to track load again.
+
+The endpoint can return:
+
+- **403 `scaling_locked`** — the sandbox is locked. See [Locking Resources](#locking-resources).
+- **409 `oom_floor`** — the requested size would force a guest OOM-kill because the current working set exceeds it. Free memory inside the guest, then retry.
+- **402 Payment Required** — the requested size exceeds your plan cap.
## In-VM Scaling
-Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale itself.
+Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale itself. Useful for workload-aware scripts where the workload knows its own demand better than the platform autoscaler can infer (e.g. "scale up before this build, back down after").
<Note>
This endpoint is only reachable from inside the sandbox. It is not exposed through the control plane API or SDKs.
@@ -71,7 +191,7 @@ Add this to your sandbox's `~/.bashrc` or inject it via `sandbox.exec.run` so ev
### Example: Custom Scaling Loop
-A simple shell script that monitors memory pressure and scales automatically. Useful when you want fine-grained control inside the sandbox itself; for the platform-managed equivalent see [Autoscaling](#autoscaling) below.
+A simple shell script that monitors memory pressure and scales automatically. Useful when you want fine-grained control inside the sandbox itself; for the platform-managed equivalent see [Autoscaling](#autoscaling) above.
```bash
#!/bin/sh
@@ -117,78 +237,64 @@ while true; do
done
```
-## Manual Scaling (Control Plane)
+## Locking Resources
-You can resize a sandbox externally from your application or operator tooling:
+If you want a sandbox to **stay at a fixed size** — predictable billing, a benchmark, a long-running pinned workload — lock it. Locking blocks both manual scaling and autoscaling on the sandbox.
-```bash
-curl -sf -X POST "$API/api/sandboxes/$SANDBOX_ID/scale" \
- -H "X-API-Key: $API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"memoryMB": 4096}'
+<CodeGroup>
+```typescript TypeScript
+await sandbox.setScalingLock(true);
```
-Response includes `autoscaleDisabled: true` if this call turned off autoscale on the sandbox (see below). The endpoint can return:
-
-- **409 `oom_floor`** — the requested size would force a guest OOM-kill because current working set exceeds it. Free memory inside the guest, then retry.
-- **403 `scaling_locked`** — the sandbox is locked (see [Locking Resources](#locking-resources)).
-
-## Autoscaling
-
-Opt a sandbox into the per-sandbox autoscaler and the platform will resize it for you based on observed memory pressure. Autoscale is **opt-in per sandbox** and **disabled by default**.
+```python Python
+await sandbox.set_scaling_lock(True)
+```
-### Enable
+```bash CLI
+oc sandbox lock sb-abc123
+```
-```bash
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
+```bash HTTP
+curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{"enabled": true, "minMemoryMB": 1024, "maxMemoryMB": 4096}'
+ -d '{"locked": true}'
```
+</CodeGroup>
-`minMemoryMB` and `maxMemoryMB` must be values from the tier table above. The autoscaler will keep the sandbox between these bounds, in tier steps.
+While locked:
-### Behavior
+- `scale` returns **403** `scaling_locked`
+- `setAutoscale({ enabled: true })` returns **403** `scaling_locked`
+- The autoscaler skips the sandbox
-- **Scale up**: when the sandbox's 1-minute average memory utilization exceeds 75 %, jump to the next tier. 60-second cooldown between up-events.
-- **Scale down**: when **all** of the 1-min, 5-min, and 15-min utilization averages stay below 25 %, drop one tier. 5-minute cooldown between down-events. Down requires at least 15 minutes of low-utilization data, so a brief idle pause won't shrink you.
-- **Manual override**: any explicit `POST /scale` call disables autoscale on that sandbox. Re-enable explicitly via `PUT /autoscale` if you want it back.
+Locking automatically disables autoscale on the sandbox, so you have a single user-facing toggle. Unlocking does **not** auto-re-enable autoscale; turn it back on explicitly if you want it.
-### Disable
+<CodeGroup>
+```typescript TypeScript
+// Unlock
+await sandbox.setScalingLock(false);
-```bash
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
- -H "X-API-Key: $API_KEY" \
- -d '{"enabled": false}'
+// Inspect
+const lock = await sandbox.getScalingLock();
+// { sandboxID: "sb-...", locked: false }
```
-### Inspect
+```python Python
+# Unlock
+await sandbox.set_scaling_lock(False)
-```bash
-curl -sf "$API/api/sandboxes/$SANDBOX_ID/autoscale" -H "X-API-Key: $API_KEY"
-# {"sandboxID":"sb-...","enabled":true,"minMemoryMB":1024,"maxMemoryMB":4096}
+# Inspect
+lock = await sandbox.get_scaling_lock()
+# {"sandboxID": "sb-...", "locked": False}
```
-## Locking Resources
-
-If you want a sandbox to **stay at a fixed size** — predictable billing, a benchmark, a long-running pinned workload — lock it. Locking blocks both manual scaling and autoscaling on the sandbox.
-
-```bash
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
- -H "X-API-Key: $API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"locked": true}'
+```bash CLI
+oc sandbox unlock sb-abc123
+oc sandbox lock-status sb-abc123
```
-While locked:
-
-- `POST /scale` returns **403** `scaling_locked`
-- `PUT /autoscale {enabled: true}` returns **403** `scaling_locked`
-- The autoscaler skips the sandbox
-
-Locking automatically disables autoscale on the sandbox, so you have a single user-facing toggle. Unlocking does **not** auto-re-enable autoscale; turn it back on explicitly if you want it.
-
-```bash
+```bash HTTP
# Unlock
curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
-H "X-API-Key: $API_KEY" \
@@ -196,5 +302,6 @@ curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
# Inspect
curl -sf "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" -H "X-API-Key: $API_KEY"
-# {"sandboxID":"sb-...","locked":true}
+# {"sandboxID":"sb-...","locked":false}
```
+</CodeGroup>
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index 80d8015c..eedade7a 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -1,6 +1,6 @@
"""OpenComputer Python SDK - cloud sandbox platform."""
-from opencomputer.sandbox import Sandbox
+from opencomputer.sandbox import Sandbox, ScalingLockedError, PlanLimitError
from opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfo
from opencomputer.filesystem import Filesystem
from opencomputer.exec import Exec, ProcessResult, ExecSession, ExecSessionInfo
@@ -25,6 +25,8 @@ from opencomputer.usage import (
__all__ = [
"Sandbox",
+ "ScalingLockedError",
+ "PlanLimitError",
"Agent",
"AgentEvent",
"AgentSession",
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 33ed532c..4fe77367 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -16,6 +16,42 @@ from opencomputer.pty import Pty
from opencomputer.sse import parse_sse_stream
+class ScalingLockedError(Exception):
+ """Raised by ``scale``, ``set_autoscale``, and other resource-changing
+ calls when the sandbox has a scaling lock active. Catch this to handle
+ the lock case specifically — typically by surfacing a clear message to
+ the user, or unlocking via ``sandbox.set_scaling_lock(False)`` first.
+ """
+
+ code = "scaling_locked"
+
+
+class PlanLimitError(Exception):
+ """Raised by ``scale`` and ``set_autoscale`` when the requested size
+ exceeds the organization's plan cap (e.g. free tier blocks > 4 GB).
+ The HTTP layer returns 402 Payment Required for this case.
+ """
+
+
+def _raise_scaling_error(resp: httpx.Response, action: str) -> None:
+ """Inspect a non-OK scaling response and raise the most specific error.
+ Falls back to ``raise_for_status`` so callers still see HTTP details for
+ unknown shapes."""
+ try:
+ body = resp.json()
+ except Exception:
+ body = {}
+ if resp.status_code == 403 and isinstance(body, dict) and body.get("code") == "scaling_locked":
+ raise ScalingLockedError(body.get("error", "scaling is locked on this sandbox"))
+ if resp.status_code == 402:
+ msg = body.get("error", "plan limit exceeded") if isinstance(body, dict) else "plan limit exceeded"
+ raise PlanLimitError(msg)
+ # Re-raise as the generic httpx error so callers get the status + body.
+ resp.raise_for_status()
+ # Defensive: shouldn't reach here on a non-OK response.
+ raise httpx.HTTPStatusError(f"failed to {action}: {resp.status_code}", request=resp.request, response=resp)
+
+
@dataclass
class Sandbox:
"""E2B-compatible sandbox interface."""
@@ -245,6 +281,127 @@ class Sandbox:
except httpx.HTTPStatusError:
return False
+ async def scale(self, memory_mb: int) -> dict:
+ """Manually resize the sandbox to a specific memory tier.
+
+ CPU is bundled with memory per the platform's tier table (e.g. 8 GB
+ → 4 vCPU). Allowed tiers: 1024, 4096, 8192, 16384, 32768, 65536 MB.
+
+ A manual scale disables autoscale on this sandbox as a side effect.
+ Re-enable with :meth:`set_autoscale` if you want size to track load.
+
+ Args:
+ memory_mb: Target memory tier in MB.
+
+ Raises:
+ ScalingLockedError: The sandbox has a scaling lock active.
+ PlanLimitError: ``memory_mb`` exceeds the org's plan cap.
+
+ Returns:
+ Dict with ``sandboxID``, ``memoryMB``, ``cpuPercent``.
+ """
+ resp = await self._client.post(
+ f"/sandboxes/{self.sandbox_id}/scale",
+ json={"memoryMB": memory_mb},
+ )
+ if resp.status_code >= 400:
+ _raise_scaling_error(resp, "scale")
+ return resp.json()
+
+ async def set_autoscale(
+ self,
+ enabled: bool,
+ *,
+ min_memory_mb: int | None = None,
+ max_memory_mb: int | None = None,
+ ) -> dict:
+ """Enable or disable per-sandbox autoscale.
+
+ When enabled, the platform resizes the sandbox between
+ ``min_memory_mb`` and ``max_memory_mb`` based on observed memory
+ pressure — scaling up fast on a 1-min spike, down slowly after
+ sustained idle.
+
+ Both bounds must be allowed memory tiers (1024, 4096, 8192, 16384,
+ 32768, 65536 MB). Pass ``enabled=False`` to turn autoscale off
+ (bounds are ignored in that case).
+
+ Args:
+ enabled: Whether autoscale should be active.
+ min_memory_mb: Lower bound when ``enabled=True``.
+ max_memory_mb: Upper bound when ``enabled=True``. Must be ≥
+ ``min_memory_mb``.
+
+ Raises:
+ ScalingLockedError: The sandbox has a scaling lock active.
+ PlanLimitError: ``max_memory_mb`` exceeds the org's plan cap.
+
+ Returns:
+ Dict with ``sandboxID``, ``enabled``, ``minMemoryMB``,
+ ``maxMemoryMB``.
+ """
+ body: dict[str, Any] = {"enabled": enabled}
+ if min_memory_mb is not None:
+ body["minMemoryMB"] = min_memory_mb
+ if max_memory_mb is not None:
+ body["maxMemoryMB"] = max_memory_mb
+ resp = await self._client.put(
+ f"/sandboxes/{self.sandbox_id}/autoscale",
+ json=body,
+ )
+ if resp.status_code >= 400:
+ _raise_scaling_error(resp, "set autoscale")
+ return resp.json()
+
+ async def get_autoscale(self) -> dict:
+ """Return the current autoscale configuration.
+
+ Returns:
+ Dict with ``sandboxID``, ``enabled``, ``minMemoryMB``,
+ ``maxMemoryMB``.
+ """
+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/autoscale")
+ resp.raise_for_status()
+ return resp.json()
+
+ async def set_scaling_lock(self, locked: bool) -> dict:
+ """Lock or unlock the sandbox's resources against scaling.
+
+ When locked:
+
+ - :meth:`scale` raises :class:`ScalingLockedError`.
+ - :meth:`set_autoscale` with ``enabled=True`` raises
+ :class:`ScalingLockedError`.
+ - The platform autoscaler skips this sandbox entirely.
+
+ Locking ALSO disables autoscale as a side effect (single-knob
+ semantics — "I don't want this scaling, period"). Unlocking does
+ NOT re-enable autoscale; call :meth:`set_autoscale` explicitly if
+ you want it back.
+
+ Args:
+ locked: ``True`` to freeze, ``False`` to allow scaling again.
+
+ Returns:
+ Dict with ``sandboxID``, ``locked``.
+ """
+ resp = await self._client.put(
+ f"/sandboxes/{self.sandbox_id}/scaling-lock",
+ json={"locked": locked},
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+ async def get_scaling_lock(self) -> dict:
+ """Return the current scaling-lock state.
+
+ Returns:
+ Dict with ``sandboxID``, ``locked``.
+ """
+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/scaling-lock")
+ resp.raise_for_status()
+ return resp.json()
+
async def set_timeout(self, timeout: int) -> None:
"""Update the sandbox timeout in seconds."""
# Route to worker directly (like commands/files/pty) — the control plane
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index e18372b5..2b8a96b4 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -1,4 +1,16 @@
-export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type PatchResult } from "./sandbox.js";
+export {
+ Sandbox,
+ ScalingLockedError,
+ PlanLimitError,
+ type SandboxOpts,
+ type CheckpointInfo,
+ type PatchInfo,
+ type PatchResult,
+ type ScaleResult,
+ type AutoscaleConfig,
+ type AutoscaleStatus,
+ type ScalingLockStatus,
+} from "./sandbox.js";
export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";
export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index d82eea2a..a56894ed 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -91,6 +91,80 @@ export interface PreviewURLResult {
createdAt: string;
}
+/**
+ * Thrown by `scale`, `setAutoscale`, and resource-changing calls when the
+ * sandbox has a scaling lock active. Catch this to handle the lock case
+ * specifically — typically by surfacing a clear message to the user, or
+ * unlocking via `sandbox.setScalingLock(false)` first.
+ */
+export class ScalingLockedError extends Error {
+ readonly code = "scaling_locked";
+ constructor(message?: string) {
+ super(message ?? "scaling is locked on this sandbox");
+ this.name = "ScalingLockedError";
+ }
+}
+
+/**
+ * Thrown by `scale` and `setAutoscale` when the requested size exceeds the
+ * organization's plan cap (e.g. free tier blocks > 4 GB). The HTTP layer
+ * returns 402 Payment Required for this case.
+ */
+export class PlanLimitError extends Error {
+ constructor(message?: string) {
+ super(message ?? "plan limit exceeded for requested resources");
+ this.name = "PlanLimitError";
+ }
+}
+
+/**
+ * Inspect a non-OK response from a scaling endpoint and throw the most
+ * specific error type. Falls back to a generic Error when the response
+ * doesn't match a known shape so callers still see the status + body.
+ */
+async function throwScalingError(resp: Response, action: string): Promise<never> {
+ const text = await resp.text();
+ let body: { error?: string; code?: string } = {};
+ try {
+ body = JSON.parse(text);
+ } catch {
+ // Non-JSON body — fall through to generic Error below.
+ }
+ if (resp.status === 403 && body.code === "scaling_locked") {
+ throw new ScalingLockedError(body.error);
+ }
+ if (resp.status === 402) {
+ throw new PlanLimitError(body.error);
+ }
+ throw new Error(`Failed to ${action}: ${resp.status} ${text}`);
+}
+
+export interface ScaleResult {
+ sandboxID: string;
+ memoryMB: number;
+ cpuPercent: number;
+}
+
+export interface AutoscaleConfig {
+ enabled: boolean;
+ /** Minimum tier the autoscaler will shrink to. Must be an allowed memory tier (1024, 4096, 8192, 16384, 32768, 65536). */
+ minMemoryMB?: number;
+ /** Maximum tier the autoscaler will grow to. Must be an allowed memory tier and ≥ minMemoryMB. */
+ maxMemoryMB?: number;
+}
+
+export interface AutoscaleStatus {
+ sandboxID: string;
+ enabled: boolean;
+ minMemoryMB: number;
+ maxMemoryMB: number;
+}
+
+export interface ScalingLockStatus {
+ sandboxID: string;
+ locked: boolean;
+}
+
export class Sandbox {
readonly sandboxId: string;
readonly agent: Agent;
@@ -326,6 +400,127 @@ export class Sandbox {
}
}
+ /**
+ * Manually resize the sandbox to a specific memory tier. CPU is bundled
+ * with memory per the platform's tier table (e.g. 8 GB → 4 vCPU). Allowed
+ * tiers: 1024, 4096, 8192, 16384, 32768, 65536 MB.
+ *
+ * Side effect: a manual scale disables autoscale on this sandbox. If you
+ * want size to track load again, call `setAutoscale({ enabled: true, ... })`
+ * after.
+ *
+ * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws
+ * `PlanLimitError` if the requested size exceeds your plan cap.
+ *
+ * [HTTP API →](/api-reference/sandboxes/scale)
+ */
+ async scale(opts: { memoryMB: number }): Promise<ScaleResult> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scale`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
+ },
+ body: JSON.stringify({ memoryMB: opts.memoryMB }),
+ });
+
+ if (!resp.ok) {
+ await throwScalingError(resp, "scale sandbox");
+ }
+
+ return resp.json();
+ }
+
+ /**
+ * Enable or disable per-sandbox autoscale. When enabled, the platform
+ * resizes the sandbox between `minMemoryMB` and `maxMemoryMB` based on
+ * observed memory pressure — scaling up fast on a 1-min spike, down
+ * slowly after sustained idle.
+ *
+ * Both bounds must be allowed memory tiers (1024, 4096, 8192, 16384,
+ * 32768, 65536). Pass `enabled: false` to turn autoscale off (bounds
+ * are ignored in that case).
+ *
+ * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws
+ * `PlanLimitError` if `maxMemoryMB` exceeds your plan cap.
+ */
+ async setAutoscale(opts: AutoscaleConfig): Promise<AutoscaleStatus> {
+ const body: Record<string, unknown> = { enabled: opts.enabled };
+ if (opts.minMemoryMB != null) body.minMemoryMB = opts.minMemoryMB;
+ if (opts.maxMemoryMB != null) body.maxMemoryMB = opts.maxMemoryMB;
+
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ await throwScalingError(resp, "set autoscale");
+ }
+
+ return resp.json();
+ }
+
+ /**
+ * Get the current autoscale configuration for the sandbox.
+ */
+ async getAutoscale(): Promise<AutoscaleStatus> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
+ });
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to get autoscale: ${resp.status} ${text}`);
+ }
+ return resp.json();
+ }
+
+ /**
+ * Lock or unlock the sandbox's resources against scaling. When locked:
+ *
+ * - `scale()` rejects with `ScalingLockedError`.
+ * - `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.
+ * - The platform autoscaler skips this sandbox entirely.
+ *
+ * Locking ALSO disables autoscale as a side effect (single-knob
+ * semantics — "I don't want this scaling, period"). Unlocking does NOT
+ * re-enable autoscale; call `setAutoscale({ enabled: true, ... })`
+ * explicitly if you want it back.
+ */
+ async setScalingLock(locked: boolean): Promise<ScalingLockStatus> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
+ },
+ body: JSON.stringify({ locked }),
+ });
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to set scaling lock: ${resp.status} ${text}`);
+ }
+ return resp.json();
+ }
+
+ /**
+ * Get the current scaling-lock state for the sandbox.
+ */
+ async getScalingLock(): Promise<ScalingLockStatus> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
+ });
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to get scaling lock: ${resp.status} ${text}`);
+ }
+ return resp.json();
+ }
+
async setTimeout(timeout: number): Promise<void> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (this.apiKey) {