Skip to content

An open-source, faster Devin alternative

TypeScript

cli and skill

Brian Reardon08b5175582e8
diff --git a/Makefile b/Makefile
index 9e7b1630..8c66c990 100644
--- a/Makefile
+++ b/Makefile
@@ -10,8 +10,8 @@ BUILD_DIR = bin
help:
@grep -E '^##' $(MAKEFILE_LIST) | sed 's/## //' | column -t -s ':'
-## build: Build server, worker, and agent binaries
-build: build-server build-worker build-agent
+## build: Build server, worker, agent, and CLI binaries
+build: build-server build-worker build-agent build-oc
## build-server: Build the control plane server
build-server:
@@ -37,6 +37,14 @@ build-agent-amd64:
build-server-arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_SERVER)-arm64 ./cmd/server
+## build-oc: Build the oc CLI tool
+build-oc:
+ CGO_ENABLED=0 go build -o $(BUILD_DIR)/oc ./cmd/oc
+
+## install-oc: Build and install oc to $GOPATH/bin
+install-oc:
+ CGO_ENABLED=0 go install ./cmd/oc
+
## --- Local Testing (3 tiers) ---
## run-dev: Tier 1 - Combined mode, no auth, no PG/NATS (simplest)
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
new file mode 100644
index 00000000..34208041
--- /dev/null
+++ b/cmd/oc/internal/client/client.go
@@ -0,0 +1,208 @@
+package client
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/gorilla/websocket"
+)
+
+type contextKey struct{}
+
+// Client is an HTTP client for the OpenComputer API.
+type Client struct {
+ baseURL string
+ apiKey string
+ token string // Bearer token for direct worker access
+ httpClient *http.Client
+}
+
+// APIError represents an error response from the API.
+type APIError struct {
+ StatusCode int
+ Message string
+}
+
+func (e *APIError) Error() string {
+ return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message)
+}
+
+// New creates a new API client.
+func New(baseURL, apiKey string) *Client {
+ baseURL = strings.TrimRight(baseURL, "/")
+ if !strings.HasSuffix(baseURL, "/api") {
+ baseURL += "/api"
+ }
+ return &Client{
+ baseURL: baseURL,
+ apiKey: apiKey,
+ httpClient: &http.Client{},
+ }
+}
+
+// WithClient stores the client in the context.
+func WithClient(ctx context.Context, c *Client) context.Context {
+ return context.WithValue(ctx, contextKey{}, c)
+}
+
+// FromContext retrieves the client from the context.
+func FromContext(ctx context.Context) *Client {
+ return ctx.Value(contextKey{}).(*Client)
+}
+
+// NewWorker creates a client that authenticates with a Bearer token directly to a worker.
+// Worker routes have no /api prefix (unlike the control plane).
+func NewWorker(connectURL, token string) *Client {
+ connectURL = strings.TrimRight(connectURL, "/")
+ return &Client{
+ baseURL: connectURL,
+ token: token,
+ httpClient: &http.Client{},
+ }
+}
+
+func (c *Client) headers() http.Header {
+ h := http.Header{}
+ if c.token != "" {
+ h.Set("Authorization", "Bearer "+c.token)
+ } else if c.apiKey != "" {
+ h.Set("X-API-Key", c.apiKey)
+ }
+ return h
+}
+
+func (c *Client) do(req *http.Request) (*http.Response, error) {
+ for k, v := range c.headers() {
+ req.Header[k] = v
+ }
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode >= 400 {
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ var errResp struct {
+ Error string `json:"error"`
+ }
+ msg := string(body)
+ if json.Unmarshal(body, &errResp) == nil && errResp.Error != "" {
+ msg = errResp.Error
+ }
+ return nil, &APIError{StatusCode: resp.StatusCode, Message: msg}
+ }
+ return resp, nil
+}
+
+// Get performs a GET request and decodes the JSON response.
+func (c *Client) Get(ctx context.Context, path string, result interface{}) error {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := c.do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if result != nil {
+ return json.NewDecoder(resp.Body).Decode(result)
+ }
+ return nil
+}
+
+// Post performs a POST request with a JSON body and decodes the response.
+func (c *Client) Post(ctx context.Context, path string, body, result interface{}) error {
+ var bodyReader io.Reader
+ if body != nil {
+ data, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ bodyReader = bytes.NewReader(data)
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, bodyReader)
+ if err != nil {
+ return err
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if result != nil {
+ return json.NewDecoder(resp.Body).Decode(result)
+ }
+ return nil
+}
+
+// Put performs a PUT request with a raw body.
+func (c *Client) Put(ctx context.Context, path string, body io.Reader) error {
+ req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, body)
+ if err != nil {
+ return err
+ }
+ resp, err := c.do(req)
+ if err != nil {
+ return err
+ }
+ resp.Body.Close()
+ return nil
+}
+
+// Delete performs a DELETE request.
+func (c *Client) Delete(ctx context.Context, path string) error {
+ req, err := http.NewRequestWithContext(ctx, "DELETE", c.baseURL+path, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := c.do(req)
+ if err != nil {
+ return err
+ }
+ resp.Body.Close()
+ return nil
+}
+
+// DeleteIgnoreNotFound performs a DELETE request, ignoring 404 errors.
+func (c *Client) DeleteIgnoreNotFound(ctx context.Context, path string) error {
+ err := c.Delete(ctx, path)
+ if err != nil {
+ if apiErr, ok := err.(*APIError); ok && apiErr.StatusCode == 404 {
+ return nil
+ }
+ }
+ return err
+}
+
+// DialWebSocket opens a WebSocket connection.
+func (c *Client) DialWebSocket(ctx context.Context, path string) (*websocket.Conn, error) {
+ wsURL := c.baseURL + path
+ wsURL = strings.Replace(wsURL, "http://", "ws://", 1)
+ wsURL = strings.Replace(wsURL, "https://", "wss://", 1)
+
+ dialer := websocket.Dialer{}
+ conn, _, err := dialer.DialContext(ctx, wsURL, c.headers())
+ if err != nil {
+ return nil, fmt.Errorf("websocket dial: %w", err)
+ }
+ return conn, nil
+}
+
+// PostRaw performs a POST with no body and returns no result (for simple actions).
+func (c *Client) PostRaw(ctx context.Context, path string) error {
+ return c.Post(ctx, path, nil, nil)
+}
+
+// BaseURL returns the client's base URL.
+func (c *Client) BaseURL() string {
+ return c.baseURL
+}
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.go
new file mode 100644
index 00000000..90a95b3d
--- /dev/null
+++ b/cmd/oc/internal/commands/checkpoint.go
@@ -0,0 +1,159 @@
+package commands
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/spf13/cobra"
+)
+
+// CheckpointInfo matches the API response for checkpoints.
+type CheckpointInfo struct {
+ ID string `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ OrgID string `json:"orgId"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ RootfsS3Key string `json:"rootfsS3Key,omitempty"`
+ WorkspaceS3Key string `json:"workspaceS3Key,omitempty"`
+ SizeBytes int64 `json:"sizeBytes"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+var checkpointCmd = &cobra.Command{
+ Use: "checkpoint",
+ Aliases: []string{"cp"},
+ Short: "Manage sandbox checkpoints",
+}
+
+var checkpointCreateCmd = &cobra.Command{
+ Use: "create <sandbox-id>",
+ Short: "Create a checkpoint of a running sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ name, _ := cmd.Flags().GetString("name")
+
+ req := map[string]string{"name": name}
+ var cp CheckpointInfo
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints", args[0]), req, &cp); err != nil {
+ return err
+ }
+
+ printer.Print(cp, func() {
+ fmt.Printf("Checkpoint created: %s (status: %s)\n", cp.ID, cp.Status)
+ fmt.Printf("Name: %s\n", cp.Name)
+ })
+ return nil
+ },
+}
+
+var checkpointListCmd = &cobra.Command{
+ Use: "list <sandbox-id>",
+ Short: "List checkpoints for a sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var checkpoints []CheckpointInfo
+ if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints", args[0]), &checkpoints); err != nil {
+ return err
+ }
+
+ printer.Print(checkpoints, func() {
+ if len(checkpoints) == 0 {
+ fmt.Println("No checkpoints found.")
+ return
+ }
+ headers := []string{"ID", "NAME", "STATUS", "SIZE", "CREATED"}
+ var rows [][]string
+ for _, cp := range checkpoints {
+ size := fmt.Sprintf("%.1f MB", float64(cp.SizeBytes)/1024/1024)
+ if cp.SizeBytes == 0 {
+ size = "-"
+ }
+ rows = append(rows, []string{
+ cp.ID,
+ cp.Name,
+ cp.Status,
+ size,
+ cp.CreatedAt.Format(time.RFC3339),
+ })
+ }
+ printer.Table(headers, rows)
+ })
+ return nil
+ },
+}
+
+var checkpointRestoreCmd = &cobra.Command{
+ Use: "restore <sandbox-id> <checkpoint-id>",
+ Short: "Restore a sandbox to a checkpoint (in-place revert)",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var result map[string]string
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints/%s/restore", args[0], args[1]), nil, &result); err != nil {
+ return err
+ }
+
+ printer.Print(result, func() {
+ fmt.Printf("Sandbox %s restored to checkpoint %s\n", args[0], args[1])
+ })
+ return nil
+ },
+}
+
+var checkpointSpawnCmd = &cobra.Command{
+ Use: "spawn <checkpoint-id>",
+ Short: "Create a new sandbox from a checkpoint",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ timeout, _ := cmd.Flags().GetInt("timeout")
+
+ req := map[string]int{"timeout": timeout}
+ var sandbox types.Sandbox
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/from-checkpoint/%s", args[0]), req, &sandbox); err != nil {
+ return err
+ }
+
+ printer.Print(sandbox, func() {
+ fmt.Printf("Created sandbox %s from checkpoint (status: %s)\n", sandbox.ID, sandbox.Status)
+ if sandbox.ConnectURL != "" {
+ fmt.Printf("Connect URL: %s\n", sandbox.ConnectURL)
+ }
+ })
+ return nil
+ },
+}
+
+var checkpointDeleteCmd = &cobra.Command{
+ Use: "delete <sandbox-id> <checkpoint-id>",
+ Short: "Delete a checkpoint",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints/%s", args[0], args[1])); err != nil {
+ return err
+ }
+ fmt.Printf("Checkpoint %s deleted.\n", args[1])
+ return nil
+ },
+}
+
+func init() {
+ checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")
+ checkpointCreateCmd.MarkFlagRequired("name")
+
+ checkpointSpawnCmd.Flags().Int("timeout", 300, "Timeout in seconds")
+
+ checkpointCmd.AddCommand(checkpointCreateCmd)
+ checkpointCmd.AddCommand(checkpointListCmd)
+ checkpointCmd.AddCommand(checkpointRestoreCmd)
+ checkpointCmd.AddCommand(checkpointSpawnCmd)
+ checkpointCmd.AddCommand(checkpointDeleteCmd)
+}
diff --git a/cmd/oc/internal/commands/config_cmd.go b/cmd/oc/internal/commands/config_cmd.go
new file mode 100644
index 00000000..6f77d34b
--- /dev/null
+++ b/cmd/oc/internal/commands/config_cmd.go
@@ -0,0 +1,65 @@
+package commands
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
+ "github.com/spf13/cobra"
+)
+
+var configCmd = &cobra.Command{
+ Use: "config",
+ Short: "Manage CLI configuration",
+}
+
+var configSetCmd = &cobra.Command{
+ Use: "set <key> <value>",
+ Short: "Set a configuration value",
+ Long: `Set a configuration value. Supported keys:
+ api-key Your OpenComputer API key
+ api-url API base URL`,
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg := config.Load(nil)
+
+ switch args[0] {
+ case "api-key":
+ cfg.APIKey = args[1]
+ case "api-url":
+ cfg.APIURL = args[1]
+ default:
+ return fmt.Errorf("unknown config key: %s (valid: api-key, api-url)", args[0])
+ }
+
+ if err := config.Save(cfg); err != nil {
+ return fmt.Errorf("saving config: %w", err)
+ }
+
+ fmt.Printf("Config %s updated.\n", args[0])
+ return nil
+ },
+}
+
+var configShowCmd = &cobra.Command{
+ Use: "show",
+ Short: "Show current configuration",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg := config.Load(cmd)
+
+ maskedKey := cfg.APIKey
+ if len(maskedKey) > 8 {
+ maskedKey = maskedKey[:4] + strings.Repeat("*", len(maskedKey)-8) + maskedKey[len(maskedKey)-4:]
+ }
+
+ fmt.Printf("API URL: %s\n", cfg.APIURL)
+ fmt.Printf("API Key: %s\n", maskedKey)
+ fmt.Printf("Config file: %s\n", config.ConfigPath())
+ return nil
+ },
+}
+
+func init() {
+ configCmd.AddCommand(configSetCmd)
+ configCmd.AddCommand(configShowCmd)
+}
diff --git a/cmd/oc/internal/commands/exec.go b/cmd/oc/internal/commands/exec.go
new file mode 100644
index 00000000..961207b6
--- /dev/null
+++ b/cmd/oc/internal/commands/exec.go
@@ -0,0 +1,82 @@
+package commands
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/spf13/cobra"
+)
+
+var execCmd = &cobra.Command{
+ Use: "exec <sandbox-id> -- <command> [args...]",
+ Short: "Execute a command in a sandbox",
+ Long: `Execute a command in a running sandbox and print the output.
+
+The command exits with the same exit code as the remote process.
+
+Examples:
+ oc exec abc123 -- echo hello
+ oc exec abc123 --cwd /app -- ls -la
+ oc exec abc123 --timeout 120 -- npm install`,
+ Args: cobra.MinimumNArgs(1),
+ DisableFlagParsing: false,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ sandboxID := args[0]
+
+ // Find the "--" separator to split sandbox flags from command
+ cmdArgs := cmd.Flags().Args()
+ var command string
+ if len(cmdArgs) > 1 {
+ command = strings.Join(cmdArgs[1:], " ")
+ } else if len(args) > 1 {
+ command = strings.Join(args[1:], " ")
+ }
+
+ if command == "" {
+ return fmt.Errorf("no command specified. Usage: oc exec <sandbox-id> -- <command>")
+ }
+
+ cwd, _ := cmd.Flags().GetString("cwd")
+ timeout, _ := cmd.Flags().GetInt("timeout")
+ envSlice, _ := cmd.Flags().GetStringSlice("env")
+
+ req := types.ProcessConfig{
+ Command: command,
+ Cwd: cwd,
+ Timeout: timeout,
+ Env: parseKVSlice(envSlice),
+ }
+
+ var result types.ProcessResult
+ if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/commands", req, &result); err != nil {
+ return err
+ }
+
+ if jsonOutput {
+ printer.PrintJSON(result)
+ } else {
+ if result.Stdout != "" {
+ fmt.Fprint(os.Stdout, result.Stdout)
+ }
+ if result.Stderr != "" {
+ fmt.Fprint(os.Stderr, result.Stderr)
+ }
+ }
+
+ if result.ExitCode != 0 {
+ os.Exit(result.ExitCode)
+ }
+ return nil
+ },
+}
+
+func init() {
+ execCmd.Flags().String("cwd", "", "Working directory")
+ execCmd.Flags().Int("timeout", 60, "Timeout in seconds")
+ execCmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
+}
diff --git a/cmd/oc/internal/commands/patch.go b/cmd/oc/internal/commands/patch.go
new file mode 100644
index 00000000..4278f867
--- /dev/null
+++ b/cmd/oc/internal/commands/patch.go
@@ -0,0 +1,135 @@
+package commands
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+// PatchInfo matches the API response for checkpoint patches.
+type PatchInfo struct {
+ ID string `json:"id"`
+ CheckpointID string `json:"checkpointId"`
+ Sequence int `json:"sequence"`
+ Script string `json:"script"`
+ Description string `json:"description"`
+ Strategy string `json:"strategy"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// PatchResult wraps the create response.
+type PatchResult struct {
+ Patch PatchInfo `json:"patch"`
+}
+
+var patchCmd = &cobra.Command{
+ Use: "patch",
+ Short: "Manage checkpoint patches",
+}
+
+var patchCreateCmd = &cobra.Command{
+ Use: "create <checkpoint-id>",
+ Short: "Create a patch for a checkpoint",
+ Long: `Create a patch script that will be applied when sandboxes are spawned from this checkpoint.
+
+Examples:
+ oc patch create <cp-id> --script=./setup.sh --description="Install deps"
+ echo "apt install -y curl" | oc patch create <cp-id> --script=-`,
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ scriptPath, _ := cmd.Flags().GetString("script")
+ description, _ := cmd.Flags().GetString("description")
+
+ var script string
+ if scriptPath == "-" {
+ data, err := io.ReadAll(os.Stdin)
+ if err != nil {
+ return fmt.Errorf("reading stdin: %w", err)
+ }
+ script = string(data)
+ } else {
+ data, err := os.ReadFile(scriptPath)
+ if err != nil {
+ return fmt.Errorf("reading script file: %w", err)
+ }
+ script = string(data)
+ }
+
+ req := map[string]string{
+ "script": script,
+ "description": description,
+ }
+ var result PatchResult
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches", args[0]), req, &result); err != nil {
+ return err
+ }
+
+ printer.Print(result, func() {
+ fmt.Printf("Patch created: %s (sequence: %d)\n", result.Patch.ID, result.Patch.Sequence)
+ })
+ return nil
+ },
+}
+
+var patchListCmd = &cobra.Command{
+ Use: "list <checkpoint-id>",
+ Short: "List patches for a checkpoint",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var patches []PatchInfo
+ if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches", args[0]), &patches); err != nil {
+ return err
+ }
+
+ printer.Print(patches, func() {
+ if len(patches) == 0 {
+ fmt.Println("No patches found.")
+ return
+ }
+ headers := []string{"ID", "SEQ", "DESCRIPTION", "STRATEGY", "CREATED"}
+ var rows [][]string
+ for _, p := range patches {
+ rows = append(rows, []string{
+ p.ID,
+ fmt.Sprintf("%d", p.Sequence),
+ p.Description,
+ p.Strategy,
+ p.CreatedAt.Format(time.RFC3339),
+ })
+ }
+ printer.Table(headers, rows)
+ })
+ return nil
+ },
+}
+
+var patchDeleteCmd = &cobra.Command{
+ Use: "delete <checkpoint-id> <patch-id>",
+ Short: "Delete a patch",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches/%s", args[0], args[1])); err != nil {
+ return err
+ }
+ fmt.Printf("Patch %s deleted.\n", args[1])
+ return nil
+ },
+}
+
+func init() {
+ patchCreateCmd.Flags().String("script", "", "Path to script file, or '-' for stdin (required)")
+ patchCreateCmd.Flags().String("description", "", "Description of the patch")
+ patchCreateCmd.MarkFlagRequired("script")
+
+ patchCmd.AddCommand(patchCreateCmd)
+ patchCmd.AddCommand(patchListCmd)
+ patchCmd.AddCommand(patchDeleteCmd)
+}
diff --git a/cmd/oc/internal/commands/preview.go b/cmd/oc/internal/commands/preview.go
new file mode 100644
index 00000000..57efc739
--- /dev/null
+++ b/cmd/oc/internal/commands/preview.go
@@ -0,0 +1,124 @@
+package commands
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+// PreviewURL matches the API response for preview URLs.
+type PreviewURL struct {
+ ID string `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ OrgID string `json:"orgId"`
+ Hostname string `json:"hostname"`
+ CustomHostname string `json:"customHostname,omitempty"`
+ Port int `json:"port"`
+ CfHostnameID string `json:"cfHostnameId,omitempty"`
+ SSLStatus string `json:"sslStatus"`
+ AuthConfig map[string]any `json:"authConfig,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+var previewCmd = &cobra.Command{
+ Use: "preview",
+ Short: "Manage sandbox preview URLs",
+}
+
+var previewCreateCmd = &cobra.Command{
+ Use: "create <sandbox-id>",
+ Short: "Create a preview URL for a sandbox port",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ port, _ := cmd.Flags().GetInt("port")
+ domain, _ := cmd.Flags().GetString("domain")
+
+ req := map[string]any{
+ "port": port,
+ "authConfig": map[string]any{},
+ }
+ if domain != "" {
+ req["domain"] = domain
+ }
+
+ var preview PreviewURL
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview", args[0]), req, &preview); err != nil {
+ return err
+ }
+
+ printer.Print(preview, func() {
+ fmt.Printf("Preview URL created:\n")
+ fmt.Printf(" Hostname: %s\n", preview.Hostname)
+ fmt.Printf(" Port: %d\n", preview.Port)
+ fmt.Printf(" SSL: %s\n", preview.SSLStatus)
+ if preview.CustomHostname != "" {
+ fmt.Printf(" Custom: %s\n", preview.CustomHostname)
+ }
+ })
+ return nil
+ },
+}
+
+var previewListCmd = &cobra.Command{
+ Use: "list <sandbox-id>",
+ Short: "List preview URLs for a sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var previews []PreviewURL
+ if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview", args[0]), &previews); err != nil {
+ return err
+ }
+
+ printer.Print(previews, func() {
+ if len(previews) == 0 {
+ fmt.Println("No preview URLs found.")
+ return
+ }
+ headers := []string{"PORT", "HOSTNAME", "SSL", "CREATED"}
+ var rows [][]string
+ for _, p := range previews {
+ hostname := p.Hostname
+ if p.CustomHostname != "" {
+ hostname = p.CustomHostname
+ }
+ rows = append(rows, []string{
+ fmt.Sprintf("%d", p.Port),
+ hostname,
+ p.SSLStatus,
+ p.CreatedAt.Format(time.RFC3339),
+ })
+ }
+ printer.Table(headers, rows)
+ })
+ return nil
+ },
+}
+
+var previewDeleteCmd = &cobra.Command{
+ Use: "delete <sandbox-id> <port>",
+ Short: "Delete a preview URL",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview/%s", args[0], args[1])); err != nil {
+ return err
+ }
+ fmt.Printf("Preview URL for port %s deleted.\n", args[1])
+ return nil
+ },
+}
+
+func init() {
+ previewCreateCmd.Flags().Int("port", 0, "Container port to expose (required)")
+ previewCreateCmd.Flags().String("domain", "", "Custom domain")
+ previewCreateCmd.MarkFlagRequired("port")
+
+ previewCmd.AddCommand(previewCreateCmd)
+ previewCmd.AddCommand(previewListCmd)
+ previewCmd.AddCommand(previewDeleteCmd)
+}
diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.go
new file mode 100644
index 00000000..6d77a5ad
--- /dev/null
+++ b/cmd/oc/internal/commands/root.go
@@ -0,0 +1,58 @@
+package commands
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
+ "github.com/spf13/cobra"
+)
+
+var (
+ jsonOutput bool
+ printer *output.Printer
+)
+
+var rootCmd = &cobra.Command{
+ Use: "oc",
+ Short: "OpenComputer CLI — manage cloud sandboxes",
+ Long: "Command-line interface for creating and managing OpenComputer sandboxes.",
+ PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
+ cfg := config.Load(cmd)
+ if cfg.APIKey == "" && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {
+ fmt.Fprintln(os.Stderr, "Warning: no API key configured. Set OPENCOMPUTER_API_KEY or run 'oc config set api-key <key>'")
+ }
+ c := client.New(cfg.APIURL, cfg.APIKey)
+ cmd.SetContext(client.WithClient(cmd.Context(), c))
+ printer = output.New(jsonOutput)
+ return nil
+ },
+ SilenceUsage: true,
+ SilenceErrors: true,
+}
+
+func init() {
+ rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Output as JSON")
+ rootCmd.PersistentFlags().String("api-key", "", "API key (overrides OPENCOMPUTER_API_KEY)")
+ rootCmd.PersistentFlags().String("api-url", "", "API URL (overrides OPENCOMPUTER_API_URL)")
+
+ // Register command groups
+ rootCmd.AddCommand(sandboxCmd)
+ rootCmd.AddCommand(execCmd)
+ rootCmd.AddCommand(shellCmd)
+ rootCmd.AddCommand(checkpointCmd)
+ rootCmd.AddCommand(patchCmd)
+ rootCmd.AddCommand(previewCmd)
+ rootCmd.AddCommand(configCmd)
+
+ // Top-level shortcuts
+ rootCmd.AddCommand(createShortcut)
+ rootCmd.AddCommand(lsShortcut)
+}
+
+// Execute runs the root command.
+func Execute() error {
+ return rootCmd.Execute()
+}
diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.go
new file mode 100644
index 00000000..f7902e6f
--- /dev/null
+++ b/cmd/oc/internal/commands/sandbox.go
@@ -0,0 +1,246 @@
+package commands
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/spf13/cobra"
+)
+
+var sandboxCmd = &cobra.Command{
+ Use: "sandbox",
+ Short: "Manage sandboxes",
+}
+
+var sandboxCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new sandbox",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ template, _ := cmd.Flags().GetString("template")
+ timeout, _ := cmd.Flags().GetInt("timeout")
+ cpu, _ := cmd.Flags().GetInt("cpu")
+ memory, _ := cmd.Flags().GetInt("memory")
+ envSlice, _ := cmd.Flags().GetStringSlice("env")
+ metaSlice, _ := cmd.Flags().GetStringSlice("metadata")
+
+ config := types.SandboxConfig{
+ Template: template,
+ Timeout: timeout,
+ CpuCount: cpu,
+ MemoryMB: memory,
+ Envs: parseKVSlice(envSlice),
+ Metadata: parseKVSlice(metaSlice),
+ }
+
+ var sandbox types.Sandbox
+ if err := c.Post(cmd.Context(), "/sandboxes", config, &sandbox); err != nil {
+ return err
+ }
+
+ printer.Print(sandbox, func() {
+ fmt.Printf("Created sandbox %s (status: %s)\n", sandbox.ID, sandbox.Status)
+ if sandbox.ConnectURL != "" {
+ fmt.Printf("Connect URL: %s\n", sandbox.ConnectURL)
+ }
+ })
+ return nil
+ },
+}
+
+var sandboxListCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List sandboxes",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var sandboxes []types.Sandbox
+ if err := c.Get(cmd.Context(), "/sandboxes", &sandboxes); err != nil {
+ return err
+ }
+
+ printer.Print(sandboxes, func() {
+ if len(sandboxes) == 0 {
+ fmt.Println("No sandboxes found.")
+ return
+ }
+ headers := []string{"ID", "TEMPLATE", "STATUS", "CPU", "MEM", "AGE"}
+ var rows [][]string
+ for _, s := range sandboxes {
+ age := time.Since(s.StartedAt).Truncate(time.Second).String()
+ rows = append(rows, []string{
+ s.ID,
+ s.Template,
+ string(s.Status),
+ fmt.Sprintf("%d", s.CpuCount),
+ fmt.Sprintf("%dMB", s.MemoryMB),
+ age,
+ })
+ }
+ printer.Table(headers, rows)
+ })
+ return nil
+ },
+}
+
+var sandboxGetCmd = &cobra.Command{
+ Use: "get <sandbox-id>",
+ Short: "Get sandbox details",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var sandbox types.Sandbox
+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0], &sandbox); err != nil {
+ return err
+ }
+
+ printer.Print(sandbox, func() {
+ fmt.Printf("ID: %s\n", sandbox.ID)
+ fmt.Printf("Template: %s\n", sandbox.Template)
+ fmt.Printf("Status: %s\n", sandbox.Status)
+ fmt.Printf("CPU: %d\n", sandbox.CpuCount)
+ fmt.Printf("Memory: %dMB\n", sandbox.MemoryMB)
+ fmt.Printf("Started: %s\n", sandbox.StartedAt.Format(time.RFC3339))
+ fmt.Printf("Ends: %s\n", sandbox.EndAt.Format(time.RFC3339))
+ if sandbox.ConnectURL != "" {
+ fmt.Printf("Connect: %s\n", sandbox.ConnectURL)
+ }
+ })
+ return nil
+ },
+}
+
+var sandboxKillCmd = &cobra.Command{
+ Use: "kill <sandbox-id>",
+ Short: "Kill and remove a sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.Delete(cmd.Context(), "/sandboxes/"+args[0]); err != nil {
+ return err
+ }
+ fmt.Printf("Sandbox %s killed.\n", args[0])
+ return nil
+ },
+}
+
+var sandboxHibernateCmd = &cobra.Command{
+ Use: "hibernate <sandbox-id>",
+ Short: "Hibernate a sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var info types.HibernationInfo
+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/hibernate", nil, &info); err != nil {
+ return err
+ }
+
+ printer.Print(info, func() {
+ fmt.Printf("Sandbox %s hibernated.\n", args[0])
+ if info.SizeBytes > 0 {
+ fmt.Printf("Size: %.1f MB\n", float64(info.SizeBytes)/1024/1024)
+ }
+ })
+ return nil
+ },
+}
+
+var sandboxWakeCmd = &cobra.Command{
+ Use: "wake <sandbox-id>",
+ Short: "Wake a hibernated sandbox",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ timeout, _ := cmd.Flags().GetInt("timeout")
+
+ req := types.WakeRequest{Timeout: timeout}
+ var sandbox types.Sandbox
+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/wake", req, &sandbox); err != nil {
+ return err
+ }
+
+ printer.Print(sandbox, func() {
+ fmt.Printf("Sandbox %s woke up (status: %s)\n", sandbox.ID, sandbox.Status)
+ })
+ return nil
+ },
+}
+
+var sandboxSetTimeoutCmd = &cobra.Command{
+ Use: "set-timeout <sandbox-id> <seconds>",
+ Short: "Update sandbox timeout",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var timeout int
+ if _, err := fmt.Sscanf(args[1], "%d", &timeout); err != nil {
+ return fmt.Errorf("invalid timeout: %s", args[1])
+ }
+
+ req := types.TimeoutRequest{Timeout: timeout}
+ if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/timeout", req, nil); err != nil {
+ return err
+ }
+
+ fmt.Printf("Timeout updated to %ds for sandbox %s\n", timeout, args[0])
+ return nil
+ },
+}
+
+// Top-level shortcuts
+var createShortcut = &cobra.Command{
+ Use: "create",
+ Short: "Create a new sandbox (shortcut for 'sandbox create')",
+ RunE: sandboxCreateCmd.RunE,
+}
+
+var lsShortcut = &cobra.Command{
+ Use: "ls",
+ Short: "List sandboxes (shortcut for 'sandbox list')",
+ RunE: sandboxListCmd.RunE,
+}
+
+func init() {
+ // sandbox create flags
+ for _, cmd := range []*cobra.Command{sandboxCreateCmd, createShortcut} {
+ cmd.Flags().String("template", "base", "Template to use")
+ cmd.Flags().Int("timeout", 300, "Timeout in seconds")
+ cmd.Flags().Int("cpu", 0, "CPU count")
+ cmd.Flags().Int("memory", 0, "Memory in MB")
+ cmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
+ cmd.Flags().StringSlice("metadata", nil, "Metadata (KEY=VALUE)")
+ }
+
+ // sandbox wake flags
+ sandboxWakeCmd.Flags().Int("timeout", 300, "Timeout in seconds after wake")
+
+ sandboxCmd.AddCommand(sandboxCreateCmd)
+ sandboxCmd.AddCommand(sandboxListCmd)
+ sandboxCmd.AddCommand(sandboxGetCmd)
+ sandboxCmd.AddCommand(sandboxKillCmd)
+ sandboxCmd.AddCommand(sandboxHibernateCmd)
+ sandboxCmd.AddCommand(sandboxWakeCmd)
+ sandboxCmd.AddCommand(sandboxSetTimeoutCmd)
+}
+
+func parseKVSlice(kvs []string) map[string]string {
+ if len(kvs) == 0 {
+ return nil
+ }
+ m := make(map[string]string)
+ for _, kv := range kvs {
+ parts := strings.SplitN(kv, "=", 2)
+ if len(parts) == 2 {
+ m[parts[0]] = parts[1]
+ }
+ }
+ return m
+}
diff --git a/cmd/oc/internal/commands/shell.go b/cmd/oc/internal/commands/shell.go
new file mode 100644
index 00000000..23d56cb7
--- /dev/null
+++ b/cmd/oc/internal/commands/shell.go
@@ -0,0 +1,138 @@
+package commands
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/gorilla/websocket"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/spf13/cobra"
+ "golang.org/x/term"
+)
+
+var shellCmd = &cobra.Command{
+ Use: "shell <sandbox-id>",
+ Short: "Open an interactive shell in a sandbox",
+ Long: `Open an interactive terminal session in a running sandbox via WebSocket PTY.
+
+Examples:
+ oc shell abc123
+ oc shell abc123 --shell /bin/zsh`,
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ sandboxID := args[0]
+ shellPath, _ := cmd.Flags().GetString("shell")
+
+ // Get sandbox info to resolve connectURL for direct worker access
+ var sandbox struct {
+ ConnectURL string `json:"connectURL"`
+ Token string `json:"token"`
+ }
+ if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s", sandboxID), &sandbox); err != nil {
+ return fmt.Errorf("failed to get sandbox: %w", err)
+ }
+
+ // Use worker client if connectURL is available (server mode)
+ ptyClient := c
+ if sandbox.ConnectURL != "" {
+ ptyClient = client.NewWorker(sandbox.ConnectURL, sandbox.Token)
+ }
+
+ // Get current terminal size
+ cols, rows := 80, 24
+ if w, h, err := term.GetSize(int(os.Stdin.Fd())); err == nil {
+ cols, rows = w, h
+ }
+
+ // Create PTY session
+ req := types.PTYCreateRequest{
+ Cols: cols,
+ Rows: rows,
+ Shell: shellPath,
+ }
+ var session types.PTYSession
+ if err := ptyClient.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty", sandboxID), req, &session); err != nil {
+ return fmt.Errorf("failed to create PTY: %w", err)
+ }
+
+ // Connect WebSocket
+ wsPath := fmt.Sprintf("/sandboxes/%s/pty/%s", sandboxID, session.SessionID)
+ conn, err := ptyClient.DialWebSocket(cmd.Context(), wsPath)
+ if err != nil {
+ return fmt.Errorf("failed to connect: %w", err)
+ }
+ defer conn.Close()
+
+ // Enter raw terminal mode
+ fd := int(os.Stdin.Fd())
+ oldState, err := term.MakeRaw(fd)
+ if err != nil {
+ return fmt.Errorf("failed to enter raw mode: %w", err)
+ }
+ defer term.Restore(fd, oldState)
+
+ // Handle SIGWINCH for terminal resize
+ sigWinch := make(chan os.Signal, 1)
+ signal.Notify(sigWinch, syscall.SIGWINCH)
+ go func() {
+ for range sigWinch {
+ if w, h, err := term.GetSize(fd); err == nil {
+ resizeReq := map[string]any{"cols": w, "rows": h}
+ // Best-effort resize via HTTP POST
+ ptyClient.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty/%s/resize", sandboxID, session.SessionID), resizeReq, nil)
+ }
+ }
+ }()
+
+ done := make(chan struct{})
+
+ // Read from WebSocket → stdout
+ go func() {
+ defer close(done)
+ for {
+ _, msg, err := conn.ReadMessage()
+ if err != nil {
+ return
+ }
+ os.Stdout.Write(msg)
+ }
+ }()
+
+ // Read from stdin → WebSocket
+ go func() {
+ buf := make([]byte, 1024)
+ for {
+ n, err := os.Stdin.Read(buf)
+ if n > 0 {
+ if writeErr := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {
+ return
+ }
+ }
+ if err != nil {
+ if err != io.EOF {
+ return
+ }
+ return
+ }
+ }
+ }()
+
+ <-done
+
+ // Cleanup: kill PTY session
+ signal.Stop(sigWinch)
+ term.Restore(fd, oldState)
+ ptyClient.Delete(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty/%s", sandboxID, session.SessionID))
+
+ return nil
+ },
+}
+
+func init() {
+ shellCmd.Flags().String("shell", "", "Shell to use (default: /bin/bash)")
+}
diff --git a/cmd/oc/internal/config/config.go b/cmd/oc/internal/config/config.go
new file mode 100644
index 00000000..529510d3
--- /dev/null
+++ b/cmd/oc/internal/config/config.go
@@ -0,0 +1,80 @@
+package config
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+
+ "github.com/spf13/cobra"
+)
+
+const (
+ DefaultAPIURL = "https://app.opencomputer.dev"
+ configDir = ".oc"
+ configFile = "config.json"
+)
+
+// Config holds the resolved CLI configuration.
+type Config struct {
+ APIURL string `json:"api_url,omitempty"`
+ APIKey string `json:"api_key,omitempty"`
+}
+
+// Load resolves configuration from flags > env > config file > defaults.
+func Load(cmd *cobra.Command) Config {
+ cfg := loadFile()
+
+ // Apply defaults
+ if cfg.APIURL == "" {
+ cfg.APIURL = DefaultAPIURL
+ }
+
+ // Env overrides file
+ if v := os.Getenv("OPENCOMPUTER_API_URL"); v != "" {
+ cfg.APIURL = v
+ }
+ if v := os.Getenv("OPENCOMPUTER_API_KEY"); v != "" {
+ cfg.APIKey = v
+ }
+
+ // Flags override env
+ if cmd != nil {
+ if v, _ := cmd.Flags().GetString("api-url"); v != "" {
+ cfg.APIURL = v
+ }
+ if v, _ := cmd.Flags().GetString("api-key"); v != "" {
+ cfg.APIKey = v
+ }
+ }
+
+ return cfg
+}
+
+// ConfigPath returns the path to the config file.
+func ConfigPath() string {
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, configDir, configFile)
+}
+
+func loadFile() Config {
+ var cfg Config
+ data, err := os.ReadFile(ConfigPath())
+ if err != nil {
+ return cfg
+ }
+ json.Unmarshal(data, &cfg)
+ return cfg
+}
+
+// Save writes the config to disk.
+func Save(cfg Config) error {
+ dir := filepath.Dir(ConfigPath())
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(cfg, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(ConfigPath(), data, 0600)
+}
diff --git a/cmd/oc/internal/output/output.go b/cmd/oc/internal/output/output.go
new file mode 100644
index 00000000..b6c0ad38
--- /dev/null
+++ b/cmd/oc/internal/output/output.go
@@ -0,0 +1,58 @@
+package output
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "text/tabwriter"
+)
+
+// Printer handles output formatting (table or JSON).
+type Printer struct {
+ JSON bool
+ W io.Writer
+}
+
+// New creates a printer that writes to stdout.
+func New(jsonOutput bool) *Printer {
+ return &Printer{JSON: jsonOutput, W: os.Stdout}
+}
+
+// PrintJSON outputs v as indented JSON.
+func (p *Printer) PrintJSON(v interface{}) error {
+ enc := json.NewEncoder(p.W)
+ enc.SetIndent("", " ")
+ return enc.Encode(v)
+}
+
+// Table prints a table with headers and rows.
+func (p *Printer) Table(headers []string, rows [][]string) {
+ w := tabwriter.NewWriter(p.W, 0, 4, 2, ' ', 0)
+ for i, h := range headers {
+ if i > 0 {
+ fmt.Fprint(w, "\t")
+ }
+ fmt.Fprint(w, h)
+ }
+ fmt.Fprintln(w)
+ for _, row := range rows {
+ for i, col := range row {
+ if i > 0 {
+ fmt.Fprint(w, "\t")
+ }
+ fmt.Fprint(w, col)
+ }
+ fmt.Fprintln(w)
+ }
+ w.Flush()
+}
+
+// Print outputs v as JSON if --json is set, otherwise calls the fallback.
+func (p *Printer) Print(v interface{}, tableFn func()) {
+ if p.JSON {
+ p.PrintJSON(v)
+ return
+ }
+ tableFn()
+}
diff --git a/cmd/oc/main.go b/cmd/oc/main.go
new file mode 100644
index 00000000..4ad267ad
--- /dev/null
+++ b/cmd/oc/main.go
@@ -0,0 +1,15 @@
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/commands"
+)
+
+func main() {
+ if err := commands.Execute(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/go.mod b/go.mod
index 04952217..f324dff9 100644
--- a/go.mod
+++ b/go.mod
@@ -21,7 +21,10 @@ require (
github.com/nats-io/nats.go v1.48.0
github.com/prometheus/client_golang v1.20.5
github.com/redis/go-redis/v9 v9.18.0
+ github.com/spf13/cobra v1.10.2
github.com/workos/workos-go/v4 v4.46.1
+ golang.org/x/sys v0.41.0
+ golang.org/x/term v0.40.0
google.golang.org/grpc v1.69.4
google.golang.org/protobuf v1.36.3
)
@@ -47,6 +50,7 @@ require (
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/google/go-querystring v1.0.0 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
@@ -59,13 +63,13 @@ require (
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
+ github.com/spf13/pflag v1.0.9 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sync v0.13.0 // indirect
- golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.24.0 // indirect
golang.org/x/time v0.8.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
diff --git a/go.sum b/go.sum
index a60c2e8c..7dc42220 100644
--- a/go.sum
+++ b/go.sum
@@ -50,6 +50,7 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -75,6 +76,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -120,6 +123,11 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargg
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -151,6 +159,7 @@ go.opentelemetry.io/otel/trace v1.31.0 h1:ffjsj1aRouKewfr85U2aGagJ46+MvodynlQ1HY
go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06FJAsO1tJg480A=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
@@ -159,10 +168,10 @@ golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
-golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
+golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
diff --git a/internal/api/pty.go b/internal/api/pty.go
index f1a42ada..b7ecd096 100644
--- a/internal/api/pty.go
+++ b/internal/api/pty.go
@@ -137,6 +137,32 @@ func (s *Server) ptyWebSocket(c echo.Context) error {
return nil
}
+func (s *Server) resizePTY(c echo.Context) error {
+ if s.ptyManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ sessionID := c.Param("sessionID")
+
+ var req struct {
+ Cols int `json:"cols"`
+ Rows int `json:"rows"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body",
+ })
+ }
+
+ if err := s.ptyManager.Resize(sessionID, req.Cols, req.Rows); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ return c.NoContent(http.StatusOK)
+}
+
func (s *Server) killPTY(c echo.Context) error {
if s.ptyManager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
diff --git a/internal/api/router.go b/internal/api/router.go
index 5818a1c0..8d2ac88c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -165,6 +165,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// PTY
api.POST("/sandboxes/:id/pty", s.createPTY)
api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
+ api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)
api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
// Templates
diff --git a/scripts/test-cli.sh b/scripts/test-cli.sh
new file mode 100755
index 00000000..4b808229
--- /dev/null
+++ b/scripts/test-cli.sh
@@ -0,0 +1,363 @@
+#!/bin/bash
+set -euo pipefail
+
+# CLI integration test — runs against a live OpenComputer server.
+# Usage: ./scripts/test-cli.sh [api-url] [api-key]
+# e.g. ./scripts/test-cli.sh https://dev.opensandbox.ai osb_600b1a...
+# Defaults to dev.opensandbox.ai if no URL provided.
+
+API_URL="${1:?Usage: $0 <api-url> <api-key>}"
+API_KEY="${2:?Usage: $0 <api-url> <api-key>}"
+
+OC="./bin/oc --api-url $API_URL --api-key $API_KEY"
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[0;33m'
+CYAN='\033[0;36m'
+BOLD='\033[1m'
+NC='\033[0m'
+
+PASSED=0
+FAILED=0
+SANDBOX_ID=""
+CHECKPOINT_ID=""
+PATCH_ID=""
+
+info() { echo -e "${CYAN}[INFO]${NC} $*"; }
+ok() { echo -e "${GREEN}[PASS]${NC} $*"; PASSED=$((PASSED + 1)); }
+fail() { echo -e "${RED}[FAIL]${NC} $*"; FAILED=$((FAILED + 1)); }
+header() { echo -e "\n${BOLD}=== $* ===${NC}"; }
+
+cleanup() {
+ if [ -n "$SANDBOX_ID" ]; then
+ info "Cleaning up sandbox $SANDBOX_ID..."
+ $OC sandbox kill "$SANDBOX_ID" 2>/dev/null || true
+ fi
+ echo
+ echo -e "${BOLD}Results: ${GREEN}$PASSED passed${NC}, ${RED}$FAILED failed${NC}"
+ if [ "$FAILED" -gt 0 ]; then
+ exit 1
+ fi
+}
+trap cleanup EXIT
+
+# Build the CLI first
+header "Building oc CLI"
+CGO_ENABLED=0 go build -o ./bin/oc ./cmd/oc
+ok "Built ./bin/oc"
+
+# -------------------------------------------------------
+header "Sandbox Lifecycle"
+# -------------------------------------------------------
+
+# sandbox create
+info "Creating sandbox..."
+CREATE_OUT=$($OC sandbox create --json)
+SANDBOX_ID=$(echo "$CREATE_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
+if [ -n "$SANDBOX_ID" ]; then
+ ok "sandbox create → $SANDBOX_ID"
+else
+ fail "sandbox create — no sandbox ID returned"
+fi
+
+# sandbox list
+info "Listing sandboxes..."
+LIST_OUT=$($OC sandbox list --json)
+if echo "$LIST_OUT" | python3 -c "import sys,json; sandboxes=json.load(sys.stdin); assert any(s['sandboxID']=='$SANDBOX_ID' for s in sandboxes)" 2>/dev/null; then
+ ok "sandbox list — found $SANDBOX_ID"
+else
+ fail "sandbox list — $SANDBOX_ID not in list"
+fi
+
+# ls shortcut
+LS_OUT=$($OC ls --json)
+if echo "$LS_OUT" | python3 -c "import sys,json; sandboxes=json.load(sys.stdin); assert any(s['sandboxID']=='$SANDBOX_ID' for s in sandboxes)" 2>/dev/null; then
+ ok "ls shortcut — found $SANDBOX_ID"
+else
+ fail "ls shortcut — $SANDBOX_ID not in list"
+fi
+
+# sandbox get
+info "Getting sandbox..."
+GET_OUT=$($OC sandbox get "$SANDBOX_ID" --json)
+GET_STATUS=$(echo "$GET_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
+if [ "$GET_STATUS" = "running" ]; then
+ ok "sandbox get — status=running"
+else
+ fail "sandbox get — expected running, got $GET_STATUS"
+fi
+
+# sandbox set-timeout
+info "Setting timeout..."
+TIMEOUT_OUT=$($OC sandbox set-timeout "$SANDBOX_ID" 600 2>&1) || true
+if echo "$TIMEOUT_OUT" | grep -qi "updated\|timeout"; then
+ ok "sandbox set-timeout 600"
+else
+ # Some server modes require direct worker connectURL for set-timeout
+ info "sandbox set-timeout skipped (server returned: $(echo "$TIMEOUT_OUT" | head -1))"
+fi
+
+# -------------------------------------------------------
+header "Command Execution"
+# -------------------------------------------------------
+
+# exec
+info "Running command..."
+EXEC_OUT=$($OC exec "$SANDBOX_ID" -- echo hello-from-cli)
+if echo "$EXEC_OUT" | grep -q "hello-from-cli"; then
+ ok "exec 'echo hello-from-cli'"
+else
+ fail "exec — expected 'hello-from-cli', got: $EXEC_OUT"
+fi
+
+# exec with --json
+EXEC_JSON=$($OC exec "$SANDBOX_ID" --json -- whoami)
+EXEC_EXIT=$(echo "$EXEC_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['exitCode'])")
+if [ "$EXEC_EXIT" = "0" ]; then
+ ok "exec --json — exitCode=0"
+else
+ fail "exec --json — exitCode=$EXEC_EXIT"
+fi
+
+# exec with --cwd
+EXEC_CWD=$($OC exec "$SANDBOX_ID" --cwd /tmp -- pwd)
+if echo "$EXEC_CWD" | grep -q "/tmp"; then
+ ok "exec --cwd /tmp — pwd=/tmp"
+else
+ fail "exec --cwd — expected /tmp, got: $EXEC_CWD"
+fi
+
+# -------------------------------------------------------
+header "Checkpoints"
+# -------------------------------------------------------
+
+# checkpoint create
+info "Creating checkpoint..."
+CP_OUT=$($OC checkpoint create "$SANDBOX_ID" --name "cli-test-v1" --json)
+CHECKPOINT_ID=$(echo "$CP_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
+if [ -n "$CHECKPOINT_ID" ]; then
+ ok "checkpoint create → $CHECKPOINT_ID"
+else
+ fail "checkpoint create — no ID returned"
+fi
+
+# Wait for checkpoint to be ready
+info "Waiting for checkpoint to be ready..."
+for i in $(seq 1 30); do
+ CP_STATUS=$($OC checkpoint list "$SANDBOX_ID" --json | python3 -c "
+import sys,json
+cps=json.load(sys.stdin)
+for cp in cps:
+ if cp['id']=='$CHECKPOINT_ID':
+ print(cp['status'])
+ break
+" 2>/dev/null || echo "unknown")
+ if [ "$CP_STATUS" = "ready" ]; then
+ break
+ fi
+ sleep 2
+done
+
+if [ "$CP_STATUS" = "ready" ]; then
+ ok "checkpoint ready after ${i}s"
+else
+ fail "checkpoint not ready after 60s (status=$CP_STATUS)"
+fi
+
+# checkpoint list
+CP_LIST=$($OC checkpoint list "$SANDBOX_ID" --json)
+CP_COUNT=$(echo "$CP_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
+if [ "$CP_COUNT" -ge 1 ]; then
+ ok "checkpoint list — $CP_COUNT checkpoint(s)"
+else
+ fail "checkpoint list — expected >=1, got $CP_COUNT"
+fi
+
+# checkpoint list (table output)
+CP_TABLE=$($OC checkpoint list "$SANDBOX_ID")
+if echo "$CP_TABLE" | grep -q "cli-test-v1"; then
+ ok "checkpoint list (table) — shows name"
+else
+ fail "checkpoint list (table) — missing name"
+fi
+
+# -------------------------------------------------------
+header "Checkpoint Patches"
+# -------------------------------------------------------
+
+if [ -n "$CHECKPOINT_ID" ]; then
+ # patch create
+ info "Creating patch..."
+ PATCH_SCRIPT=$(mktemp)
+ echo '#!/bin/bash
+echo "patched" > /tmp/patch-marker' > "$PATCH_SCRIPT"
+
+ PATCH_OUT=$($OC patch create "$CHECKPOINT_ID" --script "$PATCH_SCRIPT" --description "CLI test patch" --json)
+ rm -f "$PATCH_SCRIPT"
+ PATCH_ID=$(echo "$PATCH_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['patch']['id'])")
+ if [ -n "$PATCH_ID" ]; then
+ ok "patch create → $PATCH_ID"
+ else
+ fail "patch create — no ID returned"
+ fi
+
+ # patch list
+ PATCH_LIST=$($OC patch list "$CHECKPOINT_ID" --json)
+ PATCH_COUNT=$(echo "$PATCH_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
+ if [ "$PATCH_COUNT" -ge 1 ]; then
+ ok "patch list — $PATCH_COUNT patch(es)"
+ else
+ fail "patch list — expected >=1, got $PATCH_COUNT"
+ fi
+
+ # patch list (table)
+ PATCH_TABLE=$($OC patch list "$CHECKPOINT_ID")
+ if echo "$PATCH_TABLE" | grep -q "CLI test patch"; then
+ ok "patch list (table) — shows description"
+ else
+ fail "patch list (table) — missing description"
+ fi
+
+ # patch delete
+ if [ -n "$PATCH_ID" ]; then
+ info "Deleting patch..."
+ if $OC patch delete "$CHECKPOINT_ID" "$PATCH_ID" 2>&1 | grep -qi "deleted"; then
+ ok "patch delete"
+ else
+ fail "patch delete"
+ fi
+ fi
+fi
+
+# -------------------------------------------------------
+header "Checkpoint Spawn"
+# -------------------------------------------------------
+
+if [ -n "$CHECKPOINT_ID" ] && [ "$CP_STATUS" = "ready" ]; then
+ info "Spawning sandbox from checkpoint..."
+ SPAWN_OUT=$($OC checkpoint spawn "$CHECKPOINT_ID" --json)
+ SPAWN_ID=$(echo "$SPAWN_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
+ if [ -n "$SPAWN_ID" ]; then
+ ok "checkpoint spawn → $SPAWN_ID"
+ # Clean up spawned sandbox
+ $OC sandbox kill "$SPAWN_ID" 2>/dev/null || true
+ ok "killed spawned sandbox"
+ else
+ fail "checkpoint spawn — no sandbox ID returned"
+ fi
+fi
+
+# -------------------------------------------------------
+header "Checkpoint Restore"
+# -------------------------------------------------------
+
+if [ -n "$CHECKPOINT_ID" ] && [ "$CP_STATUS" = "ready" ]; then
+ info "Restoring checkpoint..."
+ if $OC checkpoint restore "$SANDBOX_ID" "$CHECKPOINT_ID" 2>&1 | grep -qi "restored"; then
+ ok "checkpoint restore"
+ else
+ fail "checkpoint restore"
+ fi
+
+ # Give restore a moment to complete
+ sleep 3
+fi
+
+# -------------------------------------------------------
+header "Checkpoint Delete"
+# -------------------------------------------------------
+
+if [ -n "$CHECKPOINT_ID" ]; then
+ info "Deleting checkpoint..."
+ CP_DEL_OUT=$($OC checkpoint delete "$SANDBOX_ID" "$CHECKPOINT_ID" 2>&1) || true
+ if echo "$CP_DEL_OUT" | grep -qi "deleted"; then
+ ok "checkpoint delete"
+ else
+ # Checkpoint may already be consumed by restore
+ info "checkpoint delete skipped ($(echo "$CP_DEL_OUT" | head -1))"
+ fi
+ CHECKPOINT_ID=""
+fi
+
+# -------------------------------------------------------
+header "Preview URLs"
+# -------------------------------------------------------
+
+# preview create
+info "Creating preview URL on port 8080..."
+PREV_OUT=$($OC preview create "$SANDBOX_ID" --port 8080 --json 2>&1) || true
+if echo "$PREV_OUT" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('hostname','')" 2>/dev/null; then
+ PREV_HOST=$(echo "$PREV_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['hostname'])")
+ ok "preview create — $PREV_HOST"
+
+ # preview list
+ PREV_LIST=$($OC preview list "$SANDBOX_ID" --json)
+ PREV_COUNT=$(echo "$PREV_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
+ if [ "$PREV_COUNT" -ge 1 ]; then
+ ok "preview list — $PREV_COUNT URL(s)"
+ else
+ fail "preview list — expected >=1, got $PREV_COUNT"
+ fi
+
+ # preview delete
+ if $OC preview delete "$SANDBOX_ID" 8080 2>&1 | grep -qi "deleted"; then
+ ok "preview delete"
+ else
+ fail "preview delete"
+ fi
+else
+ info "preview create skipped (may not be configured on dev server)"
+fi
+
+# -------------------------------------------------------
+header "Hibernate & Wake"
+# -------------------------------------------------------
+
+# hibernate
+info "Hibernating sandbox..."
+HIB_OUT=$($OC sandbox hibernate "$SANDBOX_ID" --json 2>&1) || true
+if echo "$HIB_OUT" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('sandboxId','')" 2>/dev/null; then
+ ok "sandbox hibernate"
+
+ # Wait a moment for hibernation to complete
+ sleep 3
+
+ # wake
+ info "Waking sandbox..."
+ WAKE_OUT=$($OC sandbox wake "$SANDBOX_ID" --json)
+ WAKE_STATUS=$(echo "$WAKE_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
+ if [ "$WAKE_STATUS" = "running" ]; then
+ ok "sandbox wake — status=running"
+ else
+ fail "sandbox wake — expected running, got $WAKE_STATUS"
+ fi
+else
+ info "hibernate skipped (may not be supported in this mode)"
+fi
+
+# -------------------------------------------------------
+header "Config"
+# -------------------------------------------------------
+
+CONFIG_OUT=$($OC config show)
+if echo "$CONFIG_OUT" | grep -q "API URL"; then
+ ok "config show"
+else
+ fail "config show — missing API URL"
+fi
+
+# -------------------------------------------------------
+header "Cleanup"
+# -------------------------------------------------------
+
+info "Killing sandbox $SANDBOX_ID..."
+if $OC sandbox kill "$SANDBOX_ID" 2>&1 | grep -qi "killed"; then
+ ok "sandbox kill"
+ SANDBOX_ID="" # Prevent double-cleanup in trap
+else
+ fail "sandbox kill"
+fi
+
+echo
+echo -e "${BOLD}All tests complete.${NC}"
diff --git a/skills/sandbox/SKILL.md b/skills/sandbox/SKILL.md
new file mode 100644
index 00000000..d277bbe4
--- /dev/null
+++ b/skills/sandbox/SKILL.md
@@ -0,0 +1,179 @@
+---
+name: sandbox
+description: Manage OpenComputer cloud sandboxes. Use when the user wants to create, run commands in, checkpoint, or manage sandbox environments. Auto-invokes when sandboxes, remote environments, or the oc CLI are mentioned.
+allowed-tools: Bash(oc *), Bash(which oc), Read, Grep, Glob
+---
+
+You have access to the `oc` CLI for managing OpenComputer cloud sandboxes. Use it to create sandboxes, execute commands, manage checkpoints, and more.
+
+## Prerequisites
+
+The `oc` CLI must be installed and configured. Check with:
+```
+which oc
+```
+
+If not installed, build it from the OpenComputer repo:
+```
+CGO_ENABLED=0 go build -o /usr/local/bin/oc ./cmd/oc
+```
+
+Configuration requires an API key. Set it via:
+```
+oc config set api-key <key>
+```
+Or pass `--api-key` on every command. The API URL defaults to `https://app.opencomputer.dev`.
+
+## CLI Reference
+
+### Sandbox Lifecycle
+
+```bash
+# Create a sandbox (returns sandbox ID)
+oc sandbox create --template base --timeout 300 --cpu 1 --memory 512
+oc sandbox create --env KEY=VALUE --env KEY2=VALUE2
+oc create # shortcut
+
+# List running sandboxes
+oc sandbox list
+oc ls # shortcut
+
+# Get sandbox details
+oc sandbox get <sandbox-id>
+
+# Kill a sandbox
+oc sandbox kill <sandbox-id>
+
+# Hibernate (saves state to S3, can wake later)
+oc sandbox hibernate <sandbox-id>
+
+# Wake a hibernated sandbox
+oc sandbox wake <sandbox-id> --timeout 300
+
+# Update timeout
+oc sandbox set-timeout <sandbox-id> <seconds>
+```
+
+### Execute Commands
+
+```bash
+# Run a command in a sandbox
+oc exec <sandbox-id> -- echo hello
+oc exec <sandbox-id> --cwd /app -- npm install
+oc exec <sandbox-id> --timeout 120 -- make build
+oc exec <sandbox-id> --env NODE_ENV=production -- node server.js
+
+# JSON output includes exitCode, stdout, stderr
+oc exec <sandbox-id> --json -- whoami
+```
+
+### Checkpoints
+
+Checkpoints snapshot a running sandbox. You can restore to a checkpoint (in-place revert) or spawn new sandboxes from one (fork).
+
+```bash
+# Create a checkpoint
+oc checkpoint create <sandbox-id> --name "after-setup"
+
+# List checkpoints
+oc checkpoint list <sandbox-id>
+
+# Restore sandbox to a checkpoint (in-place revert)
+oc checkpoint restore <sandbox-id> <checkpoint-id>
+
+# Spawn a new sandbox from a checkpoint (fork)
+oc checkpoint spawn <checkpoint-id> --timeout 300
+
+# Delete a checkpoint
+oc checkpoint delete <sandbox-id> <checkpoint-id>
+```
+
+### Checkpoint Patches
+
+Patches are scripts applied when sandboxes are spawned from a checkpoint. Use them to customize forked environments.
+
+```bash
+# Create a patch (reads script from file)
+oc patch create <checkpoint-id> --script ./setup.sh --description "Install deps"
+
+# Create a patch from stdin
+echo "apt install -y curl" | oc patch create <checkpoint-id> --script -
+
+# List patches
+oc patch list <checkpoint-id>
+
+# Delete a patch
+oc patch delete <checkpoint-id> <patch-id>
+```
+
+### Preview URLs
+
+Expose a sandbox port via a public URL.
+
+```bash
+# Create a preview URL
+oc preview create <sandbox-id> --port 3000
+oc preview create <sandbox-id> --port 8080 --domain myapp.example.com
+
+# List preview URLs
+oc preview list <sandbox-id>
+
+# Delete a preview URL
+oc preview delete <sandbox-id> <port>
+```
+
+### Interactive Shell
+
+```bash
+# Open an interactive terminal session
+oc shell <sandbox-id>
+oc shell <sandbox-id> --shell /bin/zsh
+```
+
+### Global Flags
+
+All commands support:
+- `--json` — output as JSON instead of tables
+- `--api-key <key>` — override API key
+- `--api-url <url>` — override API URL
+
+## Workflow Patterns
+
+### Create and use a sandbox
+```bash
+ID=$(oc create --json | jq -r '.sandboxID')
+oc exec $ID -- apt update && apt install -y nodejs
+oc exec $ID -- node -e "console.log('hello')"
+oc sandbox kill $ID
+```
+
+### Checkpoint workflow (setup once, fork many)
+```bash
+# Create base environment
+ID=$(oc create --json | jq -r '.sandboxID')
+oc exec $ID -- apt update && apt install -y python3 pip
+oc exec $ID -- pip install flask
+
+# Checkpoint it
+CP=$(oc checkpoint create $ID --name "python-flask" --json | jq -r '.id')
+# Wait for checkpoint to be ready
+oc checkpoint list $ID
+
+# Spawn copies from the checkpoint
+FORK1=$(oc checkpoint spawn $CP --json | jq -r '.sandboxID')
+FORK2=$(oc checkpoint spawn $CP --json | jq -r '.sandboxID')
+```
+
+### Add a patch to customize forks
+```bash
+oc patch create $CP --script ./inject-config.sh --description "Add app config"
+# All future spawns from $CP will run inject-config.sh on boot
+```
+
+## Important Notes
+
+- Always use `--json` and parse with `jq` when you need to extract IDs or fields programmatically.
+- Sandbox IDs look like `sb-xxxxxxxx`. Checkpoint IDs are UUIDs.
+- Checkpoints take a few seconds to become `ready`. Poll with `oc checkpoint list` if needed.
+- Use `oc sandbox kill` to clean up sandboxes when done.
+- The `oc exec` command exits with the remote process exit code.