Skip to content

An open-source, faster Devin alternative

TypeScript

Replace /commands with session-based exec API

motatoes706264ed0be0
diff --git a/.gitignore b/.gitignore
index 333f3707..f6d84f67 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,6 +49,10 @@ deploy/terraform/.terraform.lock.hcl
deploy/terraform/terraform.tfstate*
deploy/terraform/terraform.tfvars
+# Dev environment state
+deploy/ec2/.dev-env-state*
+deploy/ec2/*.pem
+
# Temp files
*.tmp
*.log
diff --git a/cmd/oc/internal/commands/exec.go b/cmd/oc/internal/commands/exec.go
index db5c63af..7a5f0e58 100644
--- a/cmd/oc/internal/commands/exec.go
+++ b/cmd/oc/internal/commands/exec.go
@@ -3,6 +3,7 @@ package commands
import (
"fmt"
"os"
+ "strings"
"github.com/opensandbox/opensandbox/cmd/oc/internal/client"
"github.com/opensandbox/opensandbox/pkg/types"
@@ -12,14 +13,20 @@ import (
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.
+ Long: `Execute a command in a running sandbox using session-based exec.
-The command exits with the same exit code as the remote process.
+Creates an exec session, attaches via WebSocket, and streams output.
+Use --wait to wait for completion and exit with the process exit code.
Examples:
oc exec abc123 -- echo hello
+ oc exec abc123 --wait -- npm install
oc exec abc123 --cwd /app -- ls -la
- oc exec abc123 --timeout 120 -- npm install`,
+
+Subcommands:
+ oc exec list <sandbox-id> List active exec sessions
+ oc exec attach <sandbox-id> <session-id> Reconnect to a session
+ oc exec kill <sandbox-id> <session-id> Kill a session`,
Args: cobra.MinimumNArgs(1),
DisableFlagParsing: false,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -36,8 +43,10 @@ Examples:
cwd, _ := cmd.Flags().GetString("cwd")
timeout, _ := cmd.Flags().GetInt("timeout")
envSlice, _ := cmd.Flags().GetStringSlice("env")
+ wait, _ := cmd.Flags().GetBool("wait")
- req := types.ProcessConfig{
+ // Create exec session
+ req := types.ExecSessionCreateRequest{
Command: command,
Args: cmdArgs,
Cwd: cwd,
@@ -45,31 +54,145 @@ Examples:
Env: parseKVSlice(envSlice),
}
- var result types.ProcessResult
- if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/commands", req, &result); err != nil {
+ var sessionInfo types.ExecSessionInfo
+ if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec", req, &sessionInfo); err != nil {
+ return err
+ }
+
+ if !wait {
+ // Non-wait mode: just print session ID
+ if jsonOutput {
+ printer.PrintJSON(sessionInfo)
+ } else {
+ fmt.Printf("Session %s created (command: %s)\n", sessionInfo.SessionID, sessionInfo.Command)
+ fmt.Printf("Attach with: oc exec attach %s %s\n", sandboxID, sessionInfo.SessionID)
+ }
+ return nil
+ }
+
+ // Wait mode: use the REST API to poll for completion
+ // For simplicity, list sessions and check status until done
+ for {
+ var sessions []types.ExecSessionInfo
+ if err := c.Get(cmd.Context(), "/sandboxes/"+sandboxID+"/exec", &sessions); err != nil {
+ return err
+ }
+
+ var found *types.ExecSessionInfo
+ for i := range sessions {
+ if sessions[i].SessionID == sessionInfo.SessionID {
+ found = &sessions[i]
+ break
+ }
+ }
+
+ if found == nil {
+ return fmt.Errorf("session %s not found", sessionInfo.SessionID)
+ }
+
+ if !found.Running {
+ if jsonOutput {
+ printer.PrintJSON(found)
+ } else {
+ exitCode := 0
+ if found.ExitCode != nil {
+ exitCode = *found.ExitCode
+ }
+ fmt.Fprintf(os.Stderr, "Session %s exited with code %d\n", sessionInfo.SessionID, exitCode)
+ if exitCode != 0 {
+ os.Exit(exitCode)
+ }
+ }
+ return nil
+ }
+ }
+ },
+}
+
+var execListCmd = &cobra.Command{
+ Use: "list <sandbox-id>",
+ Short: "List active exec sessions",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ sandboxID := args[0]
+
+ var sessions []types.ExecSessionInfo
+ if err := c.Get(cmd.Context(), "/sandboxes/"+sandboxID+"/exec", &sessions); err != nil {
return err
}
if jsonOutput {
- printer.PrintJSON(result)
+ printer.PrintJSON(sessions)
} else {
- if result.Stdout != "" {
- fmt.Fprint(os.Stdout, result.Stdout)
+ if len(sessions) == 0 {
+ fmt.Println("No active exec sessions.")
+ return nil
}
- if result.Stderr != "" {
- fmt.Fprint(os.Stderr, result.Stderr)
+ for _, s := range sessions {
+ status := "running"
+ if !s.Running {
+ exitCode := 0
+ if s.ExitCode != nil {
+ exitCode = *s.ExitCode
+ }
+ status = fmt.Sprintf("exited (%d)", exitCode)
+ }
+ cmdStr := s.Command
+ if len(s.Args) > 0 {
+ cmdStr += " " + strings.Join(s.Args, " ")
+ }
+ fmt.Printf(" %s %s %s clients=%d\n", s.SessionID, status, cmdStr, s.AttachedClients)
}
}
+ return nil
+ },
+}
+
+var execAttachCmd = &cobra.Command{
+ Use: "attach <sandbox-id> <session-id>",
+ Short: "Reconnect to an exec session",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ sandboxID := args[0]
+ sessionID := args[1]
+ fmt.Fprintf(os.Stderr, "Attach to session %s on sandbox %s via WebSocket (not yet implemented in CLI)\n", sessionID, sandboxID)
+ fmt.Fprintf(os.Stderr, "Use the SDK or websocat to connect to: /sandboxes/%s/exec/%s\n", sandboxID, sessionID)
+ return nil
+ },
+}
+
+var execKillCmd = &cobra.Command{
+ Use: "kill <sandbox-id> <session-id>",
+ Short: "Kill an exec session",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ sandboxID := args[0]
+ sessionID := args[1]
- if result.ExitCode != 0 {
- os.Exit(result.ExitCode)
+ signal, _ := cmd.Flags().GetInt("signal")
+ body := map[string]int{"signal": signal}
+
+ var resp map[string]interface{}
+ if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec/"+sessionID+"/kill", body, &resp); err != nil {
+ return err
}
+
+ fmt.Printf("Session %s killed\n", sessionID)
return nil
},
}
func init() {
execCmd.Flags().String("cwd", "", "Working directory")
- execCmd.Flags().Int("timeout", 60, "Timeout in seconds")
+ execCmd.Flags().Int("timeout", 0, "Timeout in seconds (0 = no timeout)")
execCmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
+ execCmd.Flags().Bool("wait", false, "Wait for command to exit and print result")
+
+ execKillCmd.Flags().Int("signal", 9, "Signal to send (default SIGKILL=9)")
+
+ execCmd.AddCommand(execListCmd)
+ execCmd.AddCommand(execAttachCmd)
+ execCmd.AddCommand(execKillCmd)
}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 0a532b99..c2d62609 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -14,6 +14,7 @@ import (
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
fc "github.com/opensandbox/opensandbox/internal/firecracker"
+ agentpb "github.com/opensandbox/opensandbox/proto/agent"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/podman"
"github.com/opensandbox/opensandbox/internal/proxy"
@@ -66,6 +67,81 @@ func main() {
// The Firecracker manager implements sandbox.Manager
var mgr sandbox.Manager = fcMgr
+ // Initialize PTY manager using Firecracker agent gRPC
+ // Initialize exec session manager using Firecracker agent gRPC
+ execMgr := sandbox.NewAgentExecSessionManager(func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {
+ agent, err := fcMgr.GetAgent(sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)
+ }
+
+ agentPB := &agentpb.ExecSessionCreateRequest{
+ Command: req.Command,
+ Args: req.Args,
+ Envs: req.Env,
+ Cwd: req.Cwd,
+ TimeoutSeconds: int32(req.Timeout),
+ MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),
+ }
+
+ sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)
+ if err != nil {
+ return nil, fmt.Errorf("create exec session in VM: %w", err)
+ }
+
+ scrollback := sandbox.NewScrollbackBuffer(0)
+ done := make(chan struct{})
+
+ handle := &sandbox.ExecSessionHandle{
+ ID: sessionID,
+ SandboxID: sandboxID,
+ Command: req.Command,
+ Args: req.Args,
+ Running: true,
+ StartedAt: time.Now(),
+ Done: done,
+ Scrollback: scrollback,
+ OnKill: func(signal int) error {
+ return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))
+ },
+ }
+
+ // Attach to the session to pipe output into the host-side scrollback
+ go func() {
+ defer close(done)
+ stream, err := agent.ExecSessionAttach(context.Background())
+ if err != nil {
+ return
+ }
+ // Send first message with session_id
+ if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {
+ return
+ }
+ for {
+ msg, err := stream.Recv()
+ if err != nil {
+ return
+ }
+ switch msg.Type {
+ case agentpb.ExecSessionOutput_STDOUT:
+ scrollback.Write(1, msg.Data)
+ case agentpb.ExecSessionOutput_STDERR:
+ scrollback.Write(2, msg.Data)
+ case agentpb.ExecSessionOutput_EXIT:
+ exitCode := int(msg.ExitCode)
+ handle.ExitCode = &exitCode
+ handle.Running = false
+ return
+ case agentpb.ExecSessionOutput_SCROLLBACK_END:
+ // Transition from scrollback replay to live
+ }
+ }
+ }()
+
+ return handle, nil
+ })
+ defer execMgr.CloseAll()
+
// Initialize PTY manager using Firecracker agent gRPC
ptyMgr := sandbox.NewAgentPTYManager(func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {
agent, err := fcMgr.GetAgent(sandboxID)
@@ -249,7 +325,7 @@ func main() {
}
// Start gRPC server for control plane communication
- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder, store)
+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, builder, store)
grpcAddr := ":9090"
log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)
go func() {
@@ -266,7 +342,7 @@ func main() {
}
// Start HTTP server for direct SDK access
- httpServer := worker.NewHTTPServer(mgr, ptyMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain)
+ httpServer := worker.NewHTTPServer(mgr, ptyMgr, execMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain)
httpAddr := fmt.Sprintf(":%d", cfg.Port)
log.Printf("opensandbox-worker: starting HTTP server on %s", httpAddr)
go func() {
diff --git a/deploy/ec2/deploy-aws-dev.sh b/deploy/ec2/deploy-aws-dev.sh
new file mode 100755
index 00000000..2741f548
--- /dev/null
+++ b/deploy/ec2/deploy-aws-dev.sh
@@ -0,0 +1,602 @@
+#!/usr/bin/env bash
+# deploy-aws-dev.sh — Deploy a dev environment on a single EC2 instance using AWS CLI
+#
+# Provisions a bare-metal ARM64 instance, sets up OpenSandbox (server + worker),
+# and deploys the current codebase. No Terraform needed.
+#
+# Usage:
+# ./deploy/ec2/deploy-aws-dev.sh [create|deploy|status|ssh|destroy]
+#
+# Commands:
+# create — Provision EC2 instance (VPC, SG, key pair, instance)
+# deploy — Build and deploy code to the instance (re-runnable)
+# status — Show instance status and connection info
+# ssh — SSH into the instance
+# destroy — Tear down all resources
+#
+# Configuration (env vars):
+# AWS_REGION — AWS region (default: us-east-2)
+# INSTANCE_TYPE — EC2 instance type (default: a1.metal)
+# KEY_NAME — EC2 key pair name (default: opensandbox-dev-<region>)
+# API_KEY — API key for the server (default: test-key)
+# DATA_VOLUME_SIZE_GB — EBS data volume size in GB (default: 200)
+#
+# State is stored in deploy/ec2/.dev-env-state to track created resources.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+STATE_FILE="$SCRIPT_DIR/.dev-env-state-${AWS_REGION}"
+
+# Defaults
+AWS_REGION="${AWS_REGION:-us-east-2}"
+INSTANCE_TYPE="${INSTANCE_TYPE:-a1.metal}"
+KEY_NAME="${KEY_NAME:-opensandbox-dev-${AWS_REGION}}"
+API_KEY="${API_KEY:-test-key}"
+DATA_VOLUME_SIZE_GB="${DATA_VOLUME_SIZE_GB:-200}"
+PROJECT_TAG="opensandbox-dev"
+
+log() { echo "==> $*"; }
+info() { echo " $*"; }
+err() { echo "ERROR: $*" >&2; exit 1; }
+
+# --- State management ---
+
+save_state() {
+ local key="$1" value="$2"
+ if [ -f "$STATE_FILE" ] && grep -q "^${key}=" "$STATE_FILE" 2>/dev/null; then
+ sed -i.bak "s|^${key}=.*|${key}=${value}|" "$STATE_FILE"
+ rm -f "${STATE_FILE}.bak"
+ else
+ echo "${key}=${value}" >> "$STATE_FILE"
+ fi
+}
+
+load_state() {
+ local key="$1"
+ if [ -f "$STATE_FILE" ]; then
+ grep "^${key}=" "$STATE_FILE" 2>/dev/null | cut -d= -f2- || true
+ fi
+}
+
+# --- AMI lookup ---
+
+lookup_arm64_ami() {
+ log "Looking up latest Ubuntu 24.04 ARM64 AMI in ${AWS_REGION}..." >&2
+ local ami_id
+ ami_id=$(aws ec2 describe-images \
+ --region "$AWS_REGION" \
+ --owners 099720109477 \
+ --filters \
+ "Name=name,Values=ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-*" \
+ "Name=architecture,Values=arm64" \
+ "Name=state,Values=available" \
+ --query 'Images | sort_by(@, &CreationDate) | [-1].ImageId' \
+ --output text)
+
+ if [ -z "$ami_id" ] || [ "$ami_id" = "None" ]; then
+ err "Could not find Ubuntu 24.04 ARM64 AMI in ${AWS_REGION}"
+ fi
+ info "AMI: $ami_id" >&2
+ echo "$ami_id"
+}
+
+# --- Create infrastructure ---
+
+cmd_create() {
+ # Check for existing state
+ local existing_instance
+ existing_instance=$(load_state INSTANCE_ID)
+ if [ -n "$existing_instance" ]; then
+ local state
+ state=$(aws ec2 describe-instances \
+ --region "$AWS_REGION" \
+ --instance-ids "$existing_instance" \
+ --query 'Reservations[0].Instances[0].State.Name' \
+ --output text 2>/dev/null || echo "not-found")
+ if [ "$state" = "running" ] || [ "$state" = "pending" ]; then
+ info "Instance $existing_instance already exists (state: $state)"
+ info "Run '$0 deploy' to deploy code, or '$0 destroy' first to recreate."
+ cmd_status
+ return 0
+ fi
+ fi
+
+ # Pre-flight: verify instance type is available in this region
+ log "Checking ${INSTANCE_TYPE} availability in ${AWS_REGION}..."
+ local avail_azs
+ avail_azs=$(aws ec2 describe-instance-type-offerings \
+ --region "$AWS_REGION" \
+ --location-type availability-zone \
+ --filters "Name=instance-type,Values=${INSTANCE_TYPE}" \
+ --query 'InstanceTypeOfferings[].Location' --output text)
+ if [ -z "$avail_azs" ]; then
+ err "${INSTANCE_TYPE} is not available in ${AWS_REGION}. Try us-east-1 or us-east-2."
+ fi
+ info "Available in: $avail_azs"
+
+ save_state REGION "$AWS_REGION"
+ save_state INSTANCE_TYPE "$INSTANCE_TYPE"
+
+ # 1. VPC
+ log "Creating VPC..."
+ local vpc_id
+ vpc_id=$(aws ec2 create-vpc \
+ --region "$AWS_REGION" \
+ --cidr-block 10.0.0.0/16 \
+ --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${PROJECT_TAG}-vpc},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'Vpc.VpcId' --output text)
+ save_state VPC_ID "$vpc_id"
+ info "VPC: $vpc_id"
+
+ # Enable DNS hostnames
+ aws ec2 modify-vpc-attribute --region "$AWS_REGION" --vpc-id "$vpc_id" --enable-dns-hostnames '{"Value":true}'
+
+ # 2. Internet Gateway
+ log "Creating Internet Gateway..."
+ local igw_id
+ igw_id=$(aws ec2 create-internet-gateway \
+ --region "$AWS_REGION" \
+ --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${PROJECT_TAG}-igw},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'InternetGateway.InternetGatewayId' --output text)
+ aws ec2 attach-internet-gateway --region "$AWS_REGION" --internet-gateway-id "$igw_id" --vpc-id "$vpc_id"
+ save_state IGW_ID "$igw_id"
+ info "IGW: $igw_id"
+
+ # 3. Subnet (public)
+ log "Creating subnet..."
+ # Pick first AZ where the instance type is available
+ local az
+ az=$(echo "$avail_azs" | tr '\t' '\n' | head -1)
+ local subnet_id
+ subnet_id=$(aws ec2 create-subnet \
+ --region "$AWS_REGION" \
+ --vpc-id "$vpc_id" \
+ --cidr-block 10.0.1.0/24 \
+ --availability-zone "$az" \
+ --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${PROJECT_TAG}-public},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'Subnet.SubnetId' --output text)
+ aws ec2 modify-subnet-attribute --region "$AWS_REGION" --subnet-id "$subnet_id" --map-public-ip-on-launch
+ save_state SUBNET_ID "$subnet_id"
+ info "Subnet: $subnet_id ($az)"
+
+ # 4. Route table
+ log "Setting up route table..."
+ local rtb_id
+ rtb_id=$(aws ec2 create-route-table \
+ --region "$AWS_REGION" \
+ --vpc-id "$vpc_id" \
+ --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${PROJECT_TAG}-public-rt},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'RouteTable.RouteTableId' --output text)
+ aws ec2 create-route --region "$AWS_REGION" --route-table-id "$rtb_id" --destination-cidr-block 0.0.0.0/0 --gateway-id "$igw_id" > /dev/null
+ aws ec2 associate-route-table --region "$AWS_REGION" --route-table-id "$rtb_id" --subnet-id "$subnet_id" > /dev/null
+ save_state RTB_ID "$rtb_id"
+
+ # 5. Security Group
+ log "Creating security group..."
+ local sg_id
+ sg_id=$(aws ec2 create-security-group \
+ --region "$AWS_REGION" \
+ --group-name "${PROJECT_TAG}-sg" \
+ --description "OpenSandbox dev: SSH + API" \
+ --vpc-id "$vpc_id" \
+ --tag-specifications "ResourceType=security-group,Tags=[{Key=Name,Value=${PROJECT_TAG}-sg},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'GroupId' --output text)
+ # SSH
+ aws ec2 authorize-security-group-ingress --region "$AWS_REGION" --group-id "$sg_id" \
+ --protocol tcp --port 22 --cidr 0.0.0.0/0 > /dev/null
+ # API (server)
+ aws ec2 authorize-security-group-ingress --region "$AWS_REGION" --group-id "$sg_id" \
+ --protocol tcp --port 8080 --cidr 0.0.0.0/0 > /dev/null
+ # Worker direct access (SDK connectURL)
+ aws ec2 authorize-security-group-ingress --region "$AWS_REGION" --group-id "$sg_id" \
+ --protocol tcp --port 8081 --cidr 0.0.0.0/0 > /dev/null
+ save_state SG_ID "$sg_id"
+ info "SG: $sg_id"
+
+ # 6. Key pair
+ log "Creating key pair..."
+ local key_file="$SCRIPT_DIR/${KEY_NAME}.pem"
+ if aws ec2 describe-key-pairs --region "$AWS_REGION" --key-names "$KEY_NAME" &>/dev/null; then
+ info "Key pair '$KEY_NAME' already exists"
+ if [ ! -f "$key_file" ]; then
+ err "Key pair exists in AWS but local file $key_file not found. Delete the key pair in AWS or provide the .pem file."
+ fi
+ else
+ aws ec2 create-key-pair \
+ --region "$AWS_REGION" \
+ --key-name "$KEY_NAME" \
+ --query 'KeyMaterial' --output text > "$key_file"
+ chmod 600 "$key_file"
+ info "Key pair created: $key_file"
+ fi
+ save_state KEY_NAME "$KEY_NAME"
+ save_state KEY_FILE "$key_file"
+
+ # 7. AMI
+ local ami_id
+ ami_id=$(lookup_arm64_ami)
+
+ # 8. Launch instance
+ log "Launching ${INSTANCE_TYPE} instance..."
+ local instance_id
+ instance_id=$(aws ec2 run-instances \
+ --region "$AWS_REGION" \
+ --image-id "$ami_id" \
+ --instance-type "$INSTANCE_TYPE" \
+ --key-name "$KEY_NAME" \
+ --subnet-id "$subnet_id" \
+ --security-group-ids "$sg_id" \
+ --block-device-mappings \
+ "DeviceName=/dev/sda1,Ebs={VolumeSize=100,VolumeType=gp3,DeleteOnTermination=true}" \
+ "DeviceName=/dev/sdf,Ebs={VolumeSize=${DATA_VOLUME_SIZE_GB},VolumeType=gp3,DeleteOnTermination=true}" \
+ --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${PROJECT_TAG}},{Key=Project,Value=${PROJECT_TAG}}]" \
+ --query 'Instances[0].InstanceId' --output text)
+ save_state INSTANCE_ID "$instance_id"
+ info "Instance: $instance_id"
+
+ # Wait for running
+ log "Waiting for instance to be running..."
+ aws ec2 wait instance-running --region "$AWS_REGION" --instance-ids "$instance_id"
+
+ local public_ip
+ public_ip=$(aws ec2 describe-instances \
+ --region "$AWS_REGION" \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
+ save_state PUBLIC_IP "$public_ip"
+ info "Public IP: $public_ip"
+
+ # Wait for SSH
+ log "Waiting for SSH to be ready (bare-metal instances take a few minutes)..."
+ local max_attempts=60
+ for i in $(seq 1 $max_attempts); do
+ if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes \
+ -i "$key_file" ubuntu@"$public_ip" "echo ok" &>/dev/null; then
+ info "SSH ready after ~$((i * 10))s"
+ break
+ fi
+ if [ "$i" -eq "$max_attempts" ]; then
+ err "SSH not ready after $((max_attempts * 10))s. Check instance console."
+ fi
+ sleep 10
+ done
+
+ # Format and mount data volume
+ log "Setting up data volume..."
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" '
+ # Find the data volume (second NVMe or xvdf)
+ DATA_DEV=""
+ for dev in /dev/nvme1n1 /dev/xvdf; do
+ if [ -b "$dev" ]; then DATA_DEV="$dev"; break; fi
+ done
+ if [ -n "$DATA_DEV" ]; then
+ if ! sudo blkid "$DATA_DEV" 2>/dev/null | grep -q ext4; then
+ sudo mkfs.ext4 -q -L opensandbox-data "$DATA_DEV"
+ fi
+ sudo mkdir -p /data
+ if ! mountpoint -q /data; then
+ echo "LABEL=opensandbox-data /data ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab > /dev/null
+ sudo mount -a
+ fi
+ sudo mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints
+ echo "Data volume mounted at /data"
+ else
+ echo "WARNING: No data volume found, using root volume"
+ sudo mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints
+ fi
+ '
+
+ # Run setup script
+ log "Provisioning instance with setup-single-host.sh..."
+ rsync -az --delete \
+ -e "ssh -o StrictHostKeyChecking=no -i $key_file" \
+ --exclude='.git' \
+ --exclude='bin/' \
+ --exclude='node_modules/' \
+ --exclude='web/dist/' \
+ --exclude='.claude/' \
+ "$PROJECT_ROOT/" "ubuntu@${public_ip}:~/opensandbox/"
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" \
+ "sudo bash ~/opensandbox/deploy/ec2/setup-single-host.sh"
+
+ echo ""
+ echo "============================================"
+ echo " Instance created and provisioned!"
+ echo ""
+ echo " Instance: $instance_id ($INSTANCE_TYPE)"
+ echo " Region: $AWS_REGION"
+ echo " IP: $public_ip"
+ echo ""
+ echo " Next: run '$0 deploy' to build and start services"
+ echo "============================================"
+}
+
+# --- Deploy code ---
+
+cmd_deploy() {
+ local public_ip key_file
+ public_ip=$(load_state PUBLIC_IP)
+ key_file=$(load_state KEY_FILE)
+
+ if [ -z "$public_ip" ] || [ -z "$key_file" ]; then
+ err "No instance found. Run '$0 create' first."
+ fi
+
+ # Verify instance is reachable
+ if ! ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes \
+ -i "$key_file" ubuntu@"$public_ip" "echo ok" &>/dev/null; then
+ err "Cannot reach $public_ip via SSH. Instance may be stopped or IP changed."
+ fi
+
+ local branch
+ branch=$(git -C "$PROJECT_ROOT" rev-parse --abbrev-ref HEAD)
+ log "Deploying branch '$branch' to $public_ip..."
+
+ log "Step 1: Syncing code..."
+ rsync -az --delete \
+ -e "ssh -o StrictHostKeyChecking=no -i $key_file" \
+ --exclude='.git' \
+ --exclude='bin/' \
+ --exclude='node_modules/' \
+ --exclude='web/dist/' \
+ --exclude='.claude/' \
+ "$PROJECT_ROOT/" "ubuntu@${public_ip}:~/opensandbox/"
+
+ log "Step 2: Building server + worker + agent on instance..."
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" "
+ export PATH=\$PATH:/usr/local/go/bin
+ cd ~/opensandbox
+ mkdir -p bin
+ echo ' Building opensandbox-server...'
+ CGO_ENABLED=0 go build -o bin/opensandbox-server ./cmd/server/
+ echo ' Building opensandbox-worker...'
+ CGO_ENABLED=0 go build -o bin/opensandbox-worker ./cmd/worker/
+ echo ' Building osb-agent...'
+ CGO_ENABLED=0 go build -o bin/osb-agent ./cmd/agent/
+ sudo cp bin/opensandbox-server /usr/local/bin/opensandbox-server
+ sudo cp bin/opensandbox-worker /usr/local/bin/opensandbox-worker
+ sudo cp bin/osb-agent /usr/local/bin/osb-agent
+ sudo chmod +x /usr/local/bin/opensandbox-server /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent
+ echo ' Binaries installed'
+ "
+
+ log "Step 3: Building rootfs (if needed)..."
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" "
+ if [ -f /data/firecracker/images/default.ext4 ]; then
+ echo ' Rootfs already exists, skipping (delete /data/firecracker/images/default.ext4 to rebuild)'
+ else
+ export PATH=\$PATH:/usr/local/go/bin
+ cd ~/opensandbox
+ echo ' Building rootfs with Docker (takes a few minutes)...'
+ sudo bash ./deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default
+ fi
+ "
+
+ log "Step 4: Installing env files..."
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" \
+ "sudo bash ~/opensandbox/deploy/ec2/setup-dev-env.sh $API_KEY"
+
+ log "Step 5: Starting/restarting services..."
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" "
+ sudo systemctl restart opensandbox-server
+ echo ' Server started'
+ sudo systemctl restart opensandbox-worker
+ echo ' Worker started'
+ "
+
+ log "Step 6: Waiting for migrations, then seeding database..."
+ sleep 5
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" "
+ for i in \$(seq 1 15); do
+ sudo docker exec postgres psql -U opensandbox -d opensandbox -q -c 'SELECT 1 FROM orgs LIMIT 0' 2>/dev/null && break
+ echo ' Waiting for migrations...'
+ sleep 2
+ done
+ sudo docker exec postgres psql -U opensandbox -d opensandbox -q -c \"
+ INSERT INTO orgs (name, slug) VALUES ('Test Org', 'test-org') ON CONFLICT (slug) DO NOTHING;
+ INSERT INTO api_keys (org_id, key_hash, key_prefix, name)
+ SELECT id, encode(sha256('${API_KEY}'::bytea), 'hex'), '${API_KEY}', 'Dev Key'
+ FROM orgs WHERE slug = 'test-org'
+ ON CONFLICT (key_hash) DO NOTHING;
+ \" && echo ' Database seeded' || echo ' WARNING: Seed failed'
+ "
+
+ log "Step 7: Verifying health..."
+ sleep 3
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" \
+ "curl -sf http://localhost:8080/health > /dev/null 2>&1 && echo ' Server health: OK' || echo ' Server health: waiting...'"
+
+ echo ""
+ echo "============================================"
+ echo " Deployment complete!"
+ echo ""
+ echo " Server URL: http://${public_ip}:8080"
+ echo " API Key: ${API_KEY}"
+ echo ""
+ echo " Test:"
+ echo " curl -X POST http://${public_ip}:8080/api/sandboxes \\"
+ echo " -H 'Content-Type: application/json' \\"
+ echo " -H 'X-API-Key: ${API_KEY}' \\"
+ echo " -d '{\"templateID\":\"default\"}'"
+ echo ""
+ echo " SSH: $0 ssh"
+ echo " Logs: $0 ssh -- sudo journalctl -u opensandbox-worker -f"
+ echo "============================================"
+}
+
+# --- Status ---
+
+cmd_status() {
+ local instance_id public_ip region
+ instance_id=$(load_state INSTANCE_ID)
+ public_ip=$(load_state PUBLIC_IP)
+ region=$(load_state REGION)
+
+ if [ -z "$instance_id" ]; then
+ echo "No dev environment found. Run '$0 create' to set one up."
+ return 0
+ fi
+
+ local state
+ state=$(aws ec2 describe-instances \
+ --region "${region:-$AWS_REGION}" \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].State.Name' \
+ --output text 2>/dev/null || echo "not-found")
+
+ # Refresh IP if running
+ if [ "$state" = "running" ]; then
+ public_ip=$(aws ec2 describe-instances \
+ --region "${region:-$AWS_REGION}" \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
+ save_state PUBLIC_IP "$public_ip"
+ fi
+
+ echo ""
+ echo " Instance: $instance_id"
+ echo " Type: $(load_state INSTANCE_TYPE)"
+ echo " Region: ${region:-$AWS_REGION}"
+ echo " State: $state"
+ echo " Public IP: ${public_ip:-n/a}"
+ echo " Key file: $(load_state KEY_FILE)"
+ echo ""
+ if [ "$state" = "running" ]; then
+ echo " Server: http://${public_ip}:8080"
+ echo " SSH: $0 ssh"
+ fi
+ echo ""
+}
+
+# --- SSH ---
+
+cmd_ssh() {
+ local public_ip key_file
+ public_ip=$(load_state PUBLIC_IP)
+ key_file=$(load_state KEY_FILE)
+
+ if [ -z "$public_ip" ] || [ -z "$key_file" ]; then
+ err "No instance found. Run '$0 create' first."
+ fi
+
+ # Pass extra args after -- to ssh
+ shift 2>/dev/null || true
+ if [ $# -gt 0 ] && [ "$1" = "--" ]; then
+ shift
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip" "$@"
+ else
+ ssh -o StrictHostKeyChecking=no -i "$key_file" ubuntu@"$public_ip"
+ fi
+}
+
+# --- Destroy ---
+
+cmd_destroy() {
+ local region instance_id vpc_id igw_id subnet_id sg_id rtb_id key_name
+ region=$(load_state REGION)
+ region="${region:-$AWS_REGION}"
+ instance_id=$(load_state INSTANCE_ID)
+ vpc_id=$(load_state VPC_ID)
+ igw_id=$(load_state IGW_ID)
+ subnet_id=$(load_state SUBNET_ID)
+ sg_id=$(load_state SG_ID)
+ rtb_id=$(load_state RTB_ID)
+ key_name=$(load_state KEY_NAME)
+
+ if [ -z "$instance_id" ] && [ -z "$vpc_id" ]; then
+ echo "No dev environment found."
+ return 0
+ fi
+
+ echo "This will destroy the dev environment in ${region}:"
+ echo " Instance: ${instance_id:-none}"
+ echo " VPC: ${vpc_id:-none}"
+ echo ""
+ read -r -p "Are you sure? (y/N) " confirm
+ if [[ ! "$confirm" =~ ^[yY]$ ]]; then
+ echo "Cancelled."
+ return 0
+ fi
+
+ # Terminate instance
+ if [ -n "$instance_id" ]; then
+ log "Terminating instance $instance_id..."
+ aws ec2 terminate-instances --region "$region" --instance-ids "$instance_id" > /dev/null 2>&1 || true
+ aws ec2 wait instance-terminated --region "$region" --instance-ids "$instance_id" 2>/dev/null || true
+ fi
+
+ # Delete key pair
+ if [ -n "$key_name" ]; then
+ log "Deleting key pair $key_name..."
+ aws ec2 delete-key-pair --region "$region" --key-name "$key_name" 2>/dev/null || true
+ fi
+
+ # Delete subnet
+ if [ -n "$subnet_id" ]; then
+ log "Deleting subnet $subnet_id..."
+ aws ec2 delete-subnet --region "$region" --subnet-id "$subnet_id" 2>/dev/null || true
+ fi
+
+ # Delete route table
+ if [ -n "$rtb_id" ]; then
+ log "Deleting route table $rtb_id..."
+ # Disassociate first
+ local assoc_id
+ assoc_id=$(aws ec2 describe-route-tables --region "$region" --route-table-ids "$rtb_id" \
+ --query 'RouteTables[0].Associations[?!Main].RouteTableAssociationId' --output text 2>/dev/null || true)
+ if [ -n "$assoc_id" ] && [ "$assoc_id" != "None" ]; then
+ aws ec2 disassociate-route-table --region "$region" --association-id "$assoc_id" 2>/dev/null || true
+ fi
+ aws ec2 delete-route-table --region "$region" --route-table-id "$rtb_id" 2>/dev/null || true
+ fi
+
+ # Detach and delete IGW
+ if [ -n "$igw_id" ] && [ -n "$vpc_id" ]; then
+ log "Deleting internet gateway $igw_id..."
+ aws ec2 detach-internet-gateway --region "$region" --internet-gateway-id "$igw_id" --vpc-id "$vpc_id" 2>/dev/null || true
+ aws ec2 delete-internet-gateway --region "$region" --internet-gateway-id "$igw_id" 2>/dev/null || true
+ fi
+
+ # Delete security group
+ if [ -n "$sg_id" ]; then
+ log "Deleting security group $sg_id..."
+ aws ec2 delete-security-group --region "$region" --group-id "$sg_id" 2>/dev/null || true
+ fi
+
+ # Delete VPC
+ if [ -n "$vpc_id" ]; then
+ log "Deleting VPC $vpc_id..."
+ aws ec2 delete-vpc --region "$region" --vpc-id "$vpc_id" 2>/dev/null || true
+ fi
+
+ # Clean up state file
+ rm -f "$STATE_FILE"
+ log "Dev environment destroyed."
+}
+
+# --- Main ---
+
+CMD="${1:-}"
+case "$CMD" in
+ create) cmd_create ;;
+ deploy) cmd_deploy ;;
+ status) cmd_status ;;
+ ssh) shift; cmd_ssh "$@" ;;
+ destroy) cmd_destroy ;;
+ *)
+ echo "Usage: $0 {create|deploy|status|ssh|destroy}"
+ echo ""
+ echo "Quick start:"
+ echo " $0 create # Provision a1.metal in us-east-2 (~5 min)"
+ echo " $0 deploy # Build and deploy code (~3 min)"
+ echo " $0 status # Show instance info"
+ echo " $0 ssh # SSH into instance"
+ echo " $0 destroy # Tear down everything"
+ echo ""
+ echo "Environment variables:"
+ echo " AWS_REGION=$AWS_REGION INSTANCE_TYPE=$INSTANCE_TYPE API_KEY=$API_KEY"
+ exit 1
+ ;;
+esac
diff --git a/deploy/ec2/deploy-single-host.sh b/deploy/ec2/deploy-single-host.sh
index d0942089..6b933794 100755
--- a/deploy/ec2/deploy-single-host.sh
+++ b/deploy/ec2/deploy-single-host.sh
@@ -128,10 +128,12 @@ done'
# ===================================================================
echo "==> Step 4: Downloading Firecracker kernel..."
# Firecracker doesn't ship kernels in releases since v1.8+.
-# Use the quickstart kernel from the Firecracker S3 bucket.
+# Use the 5.10 "docker" kernel which includes vsock, overlayfs, and other
+# features needed for sandbox VMs. The plain vmlinux.bin is a minimal 4.14
+# kernel that lacks CONFIG_VIRTIO_VSOCKETS.
case "$REMOTE_ARCH" in
- x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux.bin" ;;
- aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux.bin" ;;
+ x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux-docker-5.10.bin" ;;
+ aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux-docker-5.10.bin" ;;
esac
$SSH "sudo mkdir -p /data/firecracker && \
diff --git a/deploy/ec2/deploy-worker.sh b/deploy/ec2/deploy-worker.sh
index d67802b3..db3718c4 100755
--- a/deploy/ec2/deploy-worker.sh
+++ b/deploy/ec2/deploy-worker.sh
@@ -46,8 +46,10 @@ $SSH "sudo mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker && \
# Optionally deploy kernel
if [ "$DEPLOY_KERNEL" = "1" ]; then
echo "==> Downloading Firecracker kernel..."
- FC_VERSION="${FC_VERSION:-v1.9.1}"
- KERNEL_URL="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/vmlinux-5.10.225.bin"
+ # Firecracker no longer ships kernels in releases since v1.8+.
+ # Use the 5.10 "docker" kernel from the S3 quickstart bucket which includes
+ # vsock, overlayfs, and other features needed for sandbox VMs.
+ KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux-docker-5.10.bin"
$SSH "sudo mkdir -p /data/firecracker && \
curl -fSL -o /tmp/vmlinux '$KERNEL_URL' && \
diff --git a/deploy/ec2/setup-dev-env.sh b/deploy/ec2/setup-dev-env.sh
index 0e44368a..1a6bb6f6 100644
--- a/deploy/ec2/setup-dev-env.sh
+++ b/deploy/ec2/setup-dev-env.sh
@@ -7,9 +7,10 @@ set -euo pipefail
API_KEY="${1:?Usage: $0 API_KEY}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-# Get private IP via IMDSv2
+# Get private + public IP via IMDSv2
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
PRIVATE_IP=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/local-ipv4)
+PUBLIC_IP=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/public-ipv4 || echo "")
KERNEL_PATH="/opt/opensandbox/vmlinux"
@@ -35,7 +36,8 @@ cat > /etc/opensandbox/worker.env << EOF
HOME=/root
OPENSANDBOX_MODE=worker
OPENSANDBOX_PORT=8081
-OPENSANDBOX_HTTP_ADDR=http://${PRIVATE_IP}:8081
+# Advertise public IP so SDKs can connect directly to the worker
+OPENSANDBOX_HTTP_ADDR=http://${PUBLIC_IP:-${PRIVATE_IP}}:8081
OPENSANDBOX_GRPC_ADVERTISE=${PRIVATE_IP}:9090
OPENSANDBOX_JWT_SECRET=dev-secret
OPENSANDBOX_WORKER_ID=w-dev-1
diff --git a/deploy/ec2/setup-single-host.sh b/deploy/ec2/setup-single-host.sh
index 2b2bc303..4327a13f 100755
--- a/deploy/ec2/setup-single-host.sh
+++ b/deploy/ec2/setup-single-host.sh
@@ -108,9 +108,12 @@ sudo chmod 666 /dev/kvm 2>/dev/null || true
echo "==> Downloading Firecracker kernel..."
sudo mkdir -p /opt/opensandbox
if [ ! -f /opt/opensandbox/vmlinux ]; then
+ # Use the 5.10 "docker" kernel which includes vsock, overlayfs, and other
+ # features needed for sandbox VMs. The plain vmlinux.bin is a minimal 4.14
+ # kernel that lacks CONFIG_VIRTIO_VSOCKETS.
case "$ARCH" in
- x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux.bin" ;;
- aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux.bin" ;;
+ x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux-docker-5.10.bin" ;;
+ aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux-docker-5.10.bin" ;;
esac
sudo curl -fSL -o /opt/opensandbox/vmlinux "$KERNEL_URL"
sudo chmod 644 /opt/opensandbox/vmlinux
@@ -129,9 +132,11 @@ if [ "$ARCH" = "aarch64" ]; then
else
sudo modprobe kvm_intel || sudo modprobe kvm_amd || true
fi
+sudo modprobe vhost_vsock || echo " vhost_vsock module not loadable"
sudo tee /etc/modules-load.d/kvm.conf > /dev/null << 'MODULES'
kvm
+vhost_vsock
MODULES
sudo tee /etc/sysctl.d/99-opensandbox.conf > /dev/null << 'SYSCTL'
diff --git a/internal/agent/exec_session.go b/internal/agent/exec_session.go
new file mode 100644
index 00000000..7c08584f
--- /dev/null
+++ b/internal/agent/exec_session.go
@@ -0,0 +1,355 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os/exec"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// execSession holds a live exec session inside the VM.
+type execSession struct {
+ id string
+ cmd *exec.Cmd
+ cancel context.CancelFunc
+ command string
+ args []string
+ started time.Time
+ scrollback *sandbox.ScrollbackBuffer
+ stdinPipe io.WriteCloser
+ exitCode *int32
+ exited chan struct{}
+
+ mu sync.Mutex
+ attachedClients int
+ lastDisconnect time.Time
+ maxRunAfterDisc time.Duration
+ disconnectTimer *time.Timer
+}
+
+// ExecSessionCreate starts a command and returns a session ID.
+func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreateRequest) (*pb.ExecSessionCreateResponse, error) {
+ sessionID := uuid.New().String()[:8]
+
+ sessCtx, cancel := context.WithCancel(context.Background())
+
+ cmd := exec.CommandContext(sessCtx, req.Command, req.Args...)
+ cmd.Dir = req.Cwd
+ if cmd.Dir == "" {
+ cmd.Dir = "/root"
+ }
+
+ // Build environment: base < sandbox-level < per-command
+ env := baseEnv()
+ s.envMu.RLock()
+ env = append(env, s.sandboxEnvs...)
+ s.envMu.RUnlock()
+ env = append(env, mapToEnv(req.Envs)...)
+ cmd.Env = env
+
+ // Set process group so we can kill the whole group
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+
+ stdinPipe, err := cmd.StdinPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("stdin pipe: %w", err)
+ }
+
+ stdoutPipe, err := cmd.StdoutPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("stdout pipe: %w", err)
+ }
+
+ stderrPipe, err := cmd.StderrPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("stderr pipe: %w", err)
+ }
+
+ maxScrollback := int(req.ScrollbackMaxBytes)
+ scrollback := sandbox.NewScrollbackBuffer(maxScrollback)
+
+ sess := &execSession{
+ id: sessionID,
+ cmd: cmd,
+ cancel: cancel,
+ command: req.Command,
+ args: req.Args,
+ started: time.Now(),
+ scrollback: scrollback,
+ stdinPipe: stdinPipe,
+ exited: make(chan struct{}),
+ }
+
+ if req.MaxRunAfterDisconnect > 0 {
+ sess.maxRunAfterDisc = time.Duration(req.MaxRunAfterDisconnect) * time.Second
+ }
+
+ if err := cmd.Start(); err != nil {
+ cancel()
+ return nil, fmt.Errorf("start command: %w", err)
+ }
+
+ s.execMu.Lock()
+ s.execSessions[sessionID] = sess
+ s.execMu.Unlock()
+
+ // Pipe stdout/stderr into scrollback buffer
+ go func() {
+ buf := make([]byte, 4096)
+ for {
+ n, err := stdoutPipe.Read(buf)
+ if n > 0 {
+ scrollback.Write(1, buf[:n])
+ }
+ if err != nil {
+ return
+ }
+ }
+ }()
+
+ go func() {
+ buf := make([]byte, 4096)
+ for {
+ n, err := stderrPipe.Read(buf)
+ if n > 0 {
+ scrollback.Write(2, buf[:n])
+ }
+ if err != nil {
+ return
+ }
+ }
+ }()
+
+ // Wait for command exit
+ go func() {
+ _ = cmd.Wait()
+ code := int32(cmd.ProcessState.ExitCode())
+ sess.mu.Lock()
+ sess.exitCode = &code
+ sess.mu.Unlock()
+ close(sess.exited)
+
+ // Schedule cleanup after 5 minutes
+ time.AfterFunc(5*time.Minute, func() {
+ s.execMu.Lock()
+ delete(s.execSessions, sessionID)
+ s.execMu.Unlock()
+ })
+ }()
+
+ // Timeout: kill after N seconds if set
+ if req.TimeoutSeconds > 0 {
+ go func() {
+ timer := time.NewTimer(time.Duration(req.TimeoutSeconds) * time.Second)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ cancel()
+ case <-sess.exited:
+ }
+ }()
+ }
+
+ return &pb.ExecSessionCreateResponse{SessionId: sessionID}, nil
+}
+
+// ExecSessionAttach implements bidi streaming: sends scrollback + live output, accepts stdin.
+func (s *Server) ExecSessionAttach(stream pb.SandboxAgent_ExecSessionAttachServer) error {
+ // First message must contain session_id
+ firstMsg, err := stream.Recv()
+ if err != nil {
+ return fmt.Errorf("recv first message: %w", err)
+ }
+
+ sessionID := firstMsg.SessionId
+ if sessionID == "" {
+ return fmt.Errorf("first message must contain session_id")
+ }
+
+ s.execMu.RLock()
+ sess, ok := s.execSessions[sessionID]
+ s.execMu.RUnlock()
+ if !ok {
+ return fmt.Errorf("exec session %s not found", sessionID)
+ }
+
+ // Increment attached clients
+ sess.mu.Lock()
+ sess.attachedClients++
+ if sess.disconnectTimer != nil {
+ sess.disconnectTimer.Stop()
+ sess.disconnectTimer = nil
+ }
+ sess.mu.Unlock()
+
+ defer func() {
+ sess.mu.Lock()
+ sess.attachedClients--
+ if sess.attachedClients == 0 {
+ sess.lastDisconnect = time.Now()
+ if sess.maxRunAfterDisc > 0 {
+ sess.disconnectTimer = time.AfterFunc(sess.maxRunAfterDisc, func() {
+ sess.cancel()
+ })
+ }
+ }
+ sess.mu.Unlock()
+ }()
+
+ // Send scrollback snapshot
+ snapshot := sess.scrollback.Snapshot()
+ for _, chunk := range snapshot {
+ outType := pb.ExecSessionOutput_STDOUT
+ if chunk.Stream == 2 {
+ outType = pb.ExecSessionOutput_STDERR
+ }
+ if err := stream.Send(&pb.ExecSessionOutput{
+ Type: outType,
+ Data: chunk.Data,
+ }); err != nil {
+ return err
+ }
+ }
+
+ // Send scrollback_end marker
+ if err := stream.Send(&pb.ExecSessionOutput{
+ Type: pb.ExecSessionOutput_SCROLLBACK_END,
+ }); err != nil {
+ return err
+ }
+
+ // Subscribe for live output
+ sub := sess.scrollback.Subscribe()
+ defer sess.scrollback.Unsubscribe(sub)
+
+ // Read stdin from client in a goroutine
+ stdinDone := make(chan struct{})
+ go func() {
+ defer close(stdinDone)
+ // Process first message's stdin if any
+ if len(firstMsg.Stdin) > 0 {
+ sess.stdinPipe.Write(firstMsg.Stdin)
+ }
+ for {
+ msg, err := stream.Recv()
+ if err != nil {
+ return
+ }
+ if len(msg.Stdin) > 0 {
+ sess.stdinPipe.Write(msg.Stdin)
+ }
+ }
+ }()
+
+ // Send live output and wait for exit
+ for {
+ select {
+ case chunk, ok := <-sub:
+ if !ok {
+ return nil
+ }
+ outType := pb.ExecSessionOutput_STDOUT
+ if chunk.Stream == 2 {
+ outType = pb.ExecSessionOutput_STDERR
+ }
+ if err := stream.Send(&pb.ExecSessionOutput{
+ Type: outType,
+ Data: chunk.Data,
+ }); err != nil {
+ return err
+ }
+
+ case <-sess.exited:
+ // Drain remaining chunks from subscriber
+ for {
+ select {
+ case chunk := <-sub:
+ outType := pb.ExecSessionOutput_STDOUT
+ if chunk.Stream == 2 {
+ outType = pb.ExecSessionOutput_STDERR
+ }
+ _ = stream.Send(&pb.ExecSessionOutput{
+ Type: outType,
+ Data: chunk.Data,
+ })
+ default:
+ goto sendExit
+ }
+ }
+ sendExit:
+ sess.mu.Lock()
+ exitCode := *sess.exitCode
+ sess.mu.Unlock()
+ _ = stream.Send(&pb.ExecSessionOutput{
+ Type: pb.ExecSessionOutput_EXIT,
+ ExitCode: exitCode,
+ })
+ return nil
+
+ case <-stdinDone:
+ // Client disconnected, stop sending
+ return nil
+
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ }
+ }
+}
+
+// ExecSessionList returns metadata for all sessions.
+func (s *Server) ExecSessionList(ctx context.Context, req *pb.ExecSessionListRequest) (*pb.ExecSessionListResponse, error) {
+ s.execMu.RLock()
+ defer s.execMu.RUnlock()
+
+ var sessions []*pb.ExecSessionInfo
+ for _, sess := range s.execSessions {
+ sess.mu.Lock()
+ info := &pb.ExecSessionInfo{
+ SessionId: sess.id,
+ Command: sess.command,
+ Args: sess.args,
+ Running: sess.exitCode == nil,
+ StartedAt: sess.started.Unix(),
+ AttachedClients: int32(sess.attachedClients),
+ }
+ if sess.exitCode != nil {
+ info.ExitCode = *sess.exitCode
+ }
+ sess.mu.Unlock()
+ sessions = append(sessions, info)
+ }
+
+ return &pb.ExecSessionListResponse{Sessions: sessions}, nil
+}
+
+// ExecSessionKill sends a signal to a session's process group.
+func (s *Server) ExecSessionKill(ctx context.Context, req *pb.ExecSessionKillRequest) (*pb.ExecSessionKillResponse, error) {
+ s.execMu.RLock()
+ sess, ok := s.execSessions[req.SessionId]
+ s.execMu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("exec session %s not found", req.SessionId)
+ }
+
+ sig := syscall.Signal(req.Signal)
+ if sig == 0 {
+ sig = syscall.SIGKILL
+ }
+
+ if sess.cmd.Process != nil {
+ // Kill the process group (-pgid)
+ _ = syscall.Kill(-sess.cmd.Process.Pid, sig)
+ }
+
+ return &pb.ExecSessionKillResponse{}, nil
+}
diff --git a/internal/agent/server.go b/internal/agent/server.go
index 94d7c447..00e62c11 100644
--- a/internal/agent/server.go
+++ b/internal/agent/server.go
@@ -43,6 +43,10 @@ type Server struct {
envMu sync.RWMutex
sandboxEnvs []string
+ // Exec sessions
+ execMu sync.RWMutex
+ execSessions map[string]*execSession
+
// PTY sessions
ptyMu sync.Mutex
ptySessions map[string]*ptySession
@@ -52,10 +56,11 @@ type Server struct {
// NewServer creates a new agent server.
func NewServer(version string) *Server {
return &Server{
- startTime: time.Now(),
- version: version,
- ptySessions: make(map[string]*ptySession),
- nextPTYPort: PTYDataPortBase,
+ startTime: time.Now(),
+ version: version,
+ execSessions: make(map[string]*execSession),
+ ptySessions: make(map[string]*ptySession),
+ nextPTYPort: PTYDataPortBase,
}
}
diff --git a/internal/api/commands.go b/internal/api/commands.go
deleted file mode 100644
index 0099ebab..00000000
--- a/internal/api/commands.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package api
-
-import (
- "context"
- "log"
- "net/http"
- "time"
-
- "github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/pkg/types"
- pb "github.com/opensandbox/opensandbox/proto/worker"
-)
-
-func (s *Server) runCommand(c echo.Context) error {
- id := c.Param("id")
-
- // Server mode: dispatch to worker via gRPC
- if s.workerRegistry != nil {
- return s.runCommandRemote(c, id)
- }
-
- if s.manager == nil {
- return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
- }
-
- var cfg types.ProcessConfig
- if err := c.Bind(&cfg); err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "invalid request body: " + err.Error(),
- })
- }
-
- if cfg.Command == "" {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "cmd is required",
- })
- }
-
- var result *types.ProcessResult
- var execErr error
-
- start := time.Now()
-
- routeOp := func(ctx context.Context) error {
- result, execErr = s.manager.Exec(ctx, id, cfg)
- return execErr
- }
-
- // Route through sandbox router (handles auto-wake, rolling timeout reset)
- if s.router != nil {
- if err := s.router.Route(c.Request().Context(), id, "exec", routeOp); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
- }
- } else {
- if err := routeOp(c.Request().Context()); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
- }
- }
-
- durationMs := int(time.Since(start).Milliseconds())
-
- // Log command to per-sandbox SQLite
- if s.sandboxDBs != nil {
- sdb, dbErr := s.sandboxDBs.Get(id)
- if dbErr == nil {
- stdoutLen := len(result.Stdout)
- stderrLen := len(result.Stderr)
- _ = sdb.LogCommand(cfg.Command, cfg.Args, cfg.Cwd, result.ExitCode, durationMs, stdoutLen, stderrLen)
- }
- }
-
- return c.JSON(http.StatusOK, result)
-}
-
-func (s *Server) runCommandRemote(c echo.Context, sandboxID string) error {
- // Wait for sandbox if it's being created asynchronously
- if v, ok := s.pendingCreates.Load(sandboxID); ok {
- pending := v.(*pendingCreate)
- select {
- case <-pending.ready:
- if pending.err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "sandbox creation failed: " + pending.err.Error(),
- })
- }
- s.pendingCreates.Delete(sandboxID)
- case <-c.Request().Context().Done():
- return c.JSON(http.StatusGatewayTimeout, map[string]string{
- "error": "timed out waiting for sandbox creation",
- })
- }
- }
-
- if s.store == nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "database not configured",
- })
- }
-
- var cfg types.ProcessConfig
- if err := c.Bind(&cfg); err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "invalid request body: " + err.Error(),
- })
- }
-
- if cfg.Command == "" {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "cmd is required",
- })
- }
-
- // Look up which worker has this sandbox
- session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
- if err != nil {
- return c.JSON(http.StatusNotFound, map[string]string{
- "error": "sandbox not found",
- })
- }
-
- client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
- if err != nil {
- log.Printf("commands: worker %s unreachable for exec: %v", session.WorkerID, err)
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "worker unreachable",
- })
- }
-
- timeout := 30 * time.Second
- if cfg.Timeout > 0 {
- timeout = time.Duration(cfg.Timeout) * time.Second
- }
- grpcCtx, cancel := context.WithTimeout(c.Request().Context(), timeout)
- defer cancel()
-
- resp, err := client.ExecCommand(grpcCtx, &pb.ExecCommandRequest{
- SandboxId: sandboxID,
- Command: cfg.Command,
- Args: cfg.Args,
- Envs: cfg.Env,
- Cwd: cfg.Cwd,
- Timeout: int32(cfg.Timeout),
- })
- if err != nil {
- log.Printf("commands: gRPC exec failed for %s: %v", sandboxID, err)
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
- }
-
- result := &types.ProcessResult{
- ExitCode: int(resp.ExitCode),
- Stdout: resp.Stdout,
- Stderr: resp.Stderr,
- }
-
- return c.JSON(http.StatusOK, result)
-}
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
new file mode 100644
index 00000000..8dd8a6a7
--- /dev/null
+++ b/internal/api/exec_session.go
@@ -0,0 +1,244 @@
+package api
+
+import (
+ "context"
+ "encoding/binary"
+ "net/http"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+func (s *Server) createExecSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+
+ var req types.ExecSessionCreateRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body: " + err.Error(),
+ })
+ }
+
+ if req.Command == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "cmd is required",
+ })
+ }
+
+ var session *sandbox.ExecSessionHandle
+
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.execSessionManager.CreateSession(id, req)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "execSessionCreate", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ }
+
+ return c.JSON(http.StatusCreated, types.ExecSessionInfo{
+ SessionID: session.ID,
+ SandboxID: id,
+ Command: session.Command,
+ Args: session.Args,
+ Running: true,
+ StartedAt: session.StartedAt.Format(time.RFC3339),
+ })
+}
+
+func (s *Server) listExecSessions(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+ sessions := s.execSessionManager.ListSessions(id)
+
+ if sessions == nil {
+ sessions = []types.ExecSessionInfo{}
+ }
+
+ return c.JSON(http.StatusOK, sessions)
+}
+
+func (s *Server) execSessionWebSocket(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+ sessionID := c.Param("sessionID")
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+
+ ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
+ if err != nil {
+ return err
+ }
+ defer ws.Close()
+
+ if session.Scrollback == nil {
+ // No scrollback (shouldn't happen with Firecracker sessions, but handle gracefully)
+ ws.WriteControl(websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, "no scrollback"),
+ time.Now().Add(time.Second))
+ return nil
+ }
+
+ // Send scrollback snapshot
+ snapshot := session.Scrollback.Snapshot()
+ for _, chunk := range snapshot {
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream // 1=stdout, 2=stderr
+ copy(msg[1:], chunk.Data)
+ if err := ws.WriteMessage(websocket.BinaryMessage, msg); err != nil {
+ return nil
+ }
+ }
+
+ // Send scrollback_end marker (0x04)
+ if err := ws.WriteMessage(websocket.BinaryMessage, []byte{0x04}); err != nil {
+ return nil
+ }
+
+ // Subscribe for live output
+ sub := session.Scrollback.Subscribe()
+ defer session.Scrollback.Unsubscribe(sub)
+
+ // Read stdin from WebSocket (0x00 prefix)
+ wsDone := make(chan struct{})
+ go func() {
+ defer close(wsDone)
+ for {
+ _, raw, err := ws.ReadMessage()
+ if err != nil {
+ return
+ }
+ if len(raw) < 1 {
+ continue
+ }
+ if raw[0] == 0x00 && len(raw) > 1 && session.StdinWriter != nil {
+ session.StdinWriter.Write(raw[1:])
+ }
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+ }
+ }()
+
+ // Send live output and exit code
+ for {
+ select {
+ case chunk, ok := <-sub:
+ if !ok {
+ return nil
+ }
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream
+ copy(msg[1:], chunk.Data)
+ if err := ws.WriteMessage(websocket.BinaryMessage, msg); err != nil {
+ return nil
+ }
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+
+ case <-session.Done:
+ // Drain remaining
+ for {
+ select {
+ case chunk := <-sub:
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream
+ copy(msg[1:], chunk.Data)
+ _ = ws.WriteMessage(websocket.BinaryMessage, msg)
+ default:
+ goto sendExit
+ }
+ }
+ sendExit:
+ // Send exit code: 0x03 + 4-byte big-endian exit code
+ exitMsg := make([]byte, 5)
+ exitMsg[0] = 0x03
+ exitCode := 0
+ if session.ExitCode != nil {
+ exitCode = *session.ExitCode
+ }
+ binary.BigEndian.PutUint32(exitMsg[1:], uint32(int32(exitCode)))
+ _ = ws.WriteMessage(websocket.BinaryMessage, exitMsg)
+
+ ws.WriteControl(websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
+ time.Now().Add(time.Second))
+ return nil
+
+ case <-wsDone:
+ return nil
+ }
+ }
+}
+
+func (s *Server) killExecSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+ sessionID := c.Param("sessionID")
+
+ var body struct {
+ Signal int `json:"signal"`
+ }
+ _ = c.Bind(&body) // optional body
+
+ if body.Signal == 0 {
+ body.Signal = 9 // SIGKILL default
+ }
+
+ routeOp := func(_ context.Context) error {
+ return s.execSessionManager.KillSession(sessionID, body.Signal)
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "execSessionKill", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ }
+
+ return c.NoContent(http.StatusNoContent)
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 2251944e..4e3518c0 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -37,6 +37,7 @@ type Server struct {
workerID string // this worker's ID
region string // this worker's region
httpAddr string // public HTTP address for direct access
+ execSessionManager *sandbox.ExecSessionManager // nil if not configured
sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager
workos *auth.WorkOSMiddleware // nil if WorkOS not configured
workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
@@ -61,6 +62,7 @@ type ServerOpts struct {
WorkerID string
Region string
HTTPAddr string
+ ExecSessionManager *sandbox.ExecSessionManager
SandboxDBs *sandbox.SandboxDBManager
Router *sandbox.SandboxRouter // nil in server-only mode
SandboxProxy *proxy.SandboxProxy // nil if subdomain routing not configured
@@ -92,6 +94,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.workerID = opts.WorkerID
s.region = opts.Region
s.httpAddr = opts.HTTPAddr
+ s.execSessionManager = opts.ExecSessionManager
s.sandboxDBs = opts.SandboxDBs
s.router = opts.Router
s.workerRegistry = opts.WorkerRegistry
@@ -152,8 +155,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes/:id/preview", s.listPreviewURLs)
api.DELETE("/sandboxes/:id/preview/:port", s.deletePreviewURL)
- // Commands
- api.POST("/sandboxes/:id/commands", s.runCommand)
+ // Exec sessions (replaces old /commands)
+ api.POST("/sandboxes/:id/exec", s.createExecSession)
+ api.GET("/sandboxes/:id/exec", s.listExecSessions)
+ api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
// Filesystem
api.GET("/sandboxes/:id/files", s.readFile)
diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go
index 63b4885c..1d79e0c4 100644
--- a/internal/auth/middleware.go
+++ b/internal/auth/middleware.go
@@ -82,13 +82,18 @@ func SandboxJWTMiddleware(jwtIssuer *JWTIssuer) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
authHeader := c.Request().Header.Get("Authorization")
- if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
+ var tokenStr string
+ if authHeader != "" && strings.HasPrefix(authHeader, "Bearer ") {
+ tokenStr = strings.TrimPrefix(authHeader, "Bearer ")
+ } else if q := c.QueryParam("token"); q != "" {
+ // Allow token as query param for WebSocket connections
+ // (browsers/Node.js WebSocket API can't set custom headers)
+ tokenStr = q
+ } else {
return c.JSON(http.StatusUnauthorized, map[string]string{
"error": "missing or invalid Authorization header",
})
}
-
- tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
claims, err := jwtIssuer.ValidateSandboxToken(tokenStr)
if err != nil {
return c.JSON(http.StatusForbidden, map[string]string{
diff --git a/internal/firecracker/agent_client.go b/internal/firecracker/agent_client.go
index af6460f5..7d4c2364 100644
--- a/internal/firecracker/agent_client.go
+++ b/internal/firecracker/agent_client.go
@@ -233,6 +233,38 @@ func (c *AgentClient) PTYKill(ctx context.Context, sessionID string) error {
return err
}
+// ExecSessionCreate creates a new exec session in the VM.
+func (c *AgentClient) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreateRequest) (string, error) {
+ resp, err := c.client.ExecSessionCreate(ctx, req)
+ if err != nil {
+ return "", err
+ }
+ return resp.SessionId, nil
+}
+
+// ExecSessionAttach connects to an exec session's bidi stream.
+func (c *AgentClient) ExecSessionAttach(ctx context.Context) (pb.SandboxAgent_ExecSessionAttachClient, error) {
+ return c.client.ExecSessionAttach(ctx)
+}
+
+// ExecSessionList lists all exec sessions in the VM.
+func (c *AgentClient) ExecSessionList(ctx context.Context) ([]*pb.ExecSessionInfo, error) {
+ resp, err := c.client.ExecSessionList(ctx, &pb.ExecSessionListRequest{})
+ if err != nil {
+ return nil, err
+ }
+ return resp.Sessions, nil
+}
+
+// ExecSessionKill kills an exec session in the VM.
+func (c *AgentClient) ExecSessionKill(ctx context.Context, sessionID string, signal int32) error {
+ _, err := c.client.ExecSessionKill(ctx, &pb.ExecSessionKillRequest{
+ SessionId: sessionID,
+ Signal: signal,
+ })
+ return err
+}
+
// ConnectPTYData connects to the PTY data stream on the given vsock port.
// Returns a raw TCP-like connection for bidirectional PTY I/O.
func (c *AgentClient) ConnectPTYData(vsockPath string, dataPort uint32) (net.Conn, error) {
diff --git a/internal/sandbox/exec_session.go b/internal/sandbox/exec_session.go
new file mode 100644
index 00000000..162ce925
--- /dev/null
+++ b/internal/sandbox/exec_session.go
@@ -0,0 +1,144 @@
+package sandbox
+
+import (
+ "fmt"
+ "io"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// ExecSessionManager manages exec sessions on the host side.
+// Mirrors PTYManager's pattern: supports both Podman (stub) and Firecracker
+// (via createFunc override).
+type ExecSessionManager struct {
+ mu sync.RWMutex
+ sessions map[string]*ExecSessionHandle
+ createFunc func(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error)
+}
+
+// ExecSessionHandle holds the state for an exec session on the host side.
+type ExecSessionHandle struct {
+ ID string
+ SandboxID string
+ Command string
+ Args []string
+ Running bool
+ ExitCode *int
+ StartedAt time.Time
+ Done chan struct{}
+ Scrollback *ScrollbackBuffer
+ StdinWriter io.Writer
+
+ OnKill func(signal int) error
+}
+
+// NewExecSessionManager creates a stub exec session manager (Podman — not supported).
+func NewExecSessionManager() *ExecSessionManager {
+ return &ExecSessionManager{
+ sessions: make(map[string]*ExecSessionHandle),
+ }
+}
+
+// NewAgentExecSessionManager creates an exec session manager that delegates to
+// a custom create function (used by Firecracker mode).
+func NewAgentExecSessionManager(createFunc func(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error)) *ExecSessionManager {
+ return &ExecSessionManager{
+ sessions: make(map[string]*ExecSessionHandle),
+ createFunc: createFunc,
+ }
+}
+
+// CreateSession creates a new exec session.
+func (m *ExecSessionManager) CreateSession(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error) {
+ if m.createFunc == nil {
+ return nil, fmt.Errorf("exec sessions not supported in Podman mode")
+ }
+
+ handle, err := m.createFunc(sandboxID, req)
+ if err != nil {
+ return nil, err
+ }
+
+ m.mu.Lock()
+ m.sessions[handle.ID] = handle
+ m.mu.Unlock()
+
+ return handle, nil
+}
+
+// GetSession returns an exec session by ID.
+func (m *ExecSessionManager) GetSession(sessionID string) (*ExecSessionHandle, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ session, ok := m.sessions[sessionID]
+ if !ok {
+ return nil, fmt.Errorf("exec session %s not found", sessionID)
+ }
+ return session, nil
+}
+
+// ListSessions returns info for all sessions belonging to a sandbox.
+func (m *ExecSessionManager) ListSessions(sandboxID string) []types.ExecSessionInfo {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ var results []types.ExecSessionInfo
+ for _, s := range m.sessions {
+ if s.SandboxID == sandboxID {
+ info := types.ExecSessionInfo{
+ SessionID: s.ID,
+ SandboxID: s.SandboxID,
+ Command: s.Command,
+ Args: s.Args,
+ Running: s.Running,
+ ExitCode: s.ExitCode,
+ StartedAt: s.StartedAt.Format(time.RFC3339),
+ }
+ results = append(results, info)
+ }
+ }
+ return results
+}
+
+// KillSession kills an exec session with the given signal.
+func (m *ExecSessionManager) KillSession(sessionID string, signal int) error {
+ m.mu.RLock()
+ session, ok := m.sessions[sessionID]
+ m.mu.RUnlock()
+ if !ok {
+ return fmt.Errorf("exec session %s not found", sessionID)
+ }
+
+ if session.OnKill != nil {
+ return session.OnKill(signal)
+ }
+ return fmt.Errorf("kill not supported for this session")
+}
+
+// CloseAll terminates all exec sessions.
+func (m *ExecSessionManager) CloseAll() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ for _, session := range m.sessions {
+ if session.OnKill != nil {
+ _ = session.OnKill(9) // SIGKILL
+ }
+ }
+ m.sessions = make(map[string]*ExecSessionHandle)
+}
+
+// RemoveSessions removes all sessions for a sandbox (used on hibernate/kill).
+func (m *ExecSessionManager) RemoveSessions(sandboxID string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ for id, s := range m.sessions {
+ if s.SandboxID == sandboxID {
+ delete(m.sessions, id)
+ }
+ }
+}
diff --git a/internal/sandbox/scrollback.go b/internal/sandbox/scrollback.go
new file mode 100644
index 00000000..f3958683
--- /dev/null
+++ b/internal/sandbox/scrollback.go
@@ -0,0 +1,102 @@
+package sandbox
+
+import "sync"
+
+// OutputChunk is a tagged output chunk with a stream identifier.
+type OutputChunk struct {
+ Stream uint8 // 1=stdout, 2=stderr
+ Data []byte
+ Seq uint64
+}
+
+// ScrollbackBuffer is a thread-safe ring buffer for exec session output.
+// It stores tagged output chunks up to a maximum total byte size and
+// supports live subscribers for fan-out.
+type ScrollbackBuffer struct {
+ mu sync.Mutex
+ chunks []OutputChunk
+ totalLen int
+ maxBytes int
+ nextSeq uint64
+ subs map[chan OutputChunk]struct{}
+}
+
+// NewScrollbackBuffer creates a new scrollback buffer with the given max size.
+// If maxBytes is 0, defaults to 1MB.
+func NewScrollbackBuffer(maxBytes int) *ScrollbackBuffer {
+ if maxBytes <= 0 {
+ maxBytes = 1024 * 1024 // 1MB
+ }
+ return &ScrollbackBuffer{
+ maxBytes: maxBytes,
+ subs: make(map[chan OutputChunk]struct{}),
+ }
+}
+
+// Write appends a chunk to the buffer and fans out to all subscribers.
+func (sb *ScrollbackBuffer) Write(stream uint8, data []byte) {
+ if len(data) == 0 {
+ return
+ }
+
+ copied := make([]byte, len(data))
+ copy(copied, data)
+
+ sb.mu.Lock()
+ chunk := OutputChunk{
+ Stream: stream,
+ Data: copied,
+ Seq: sb.nextSeq,
+ }
+ sb.nextSeq++
+ sb.chunks = append(sb.chunks, chunk)
+ sb.totalLen += len(copied)
+
+ // Evict oldest chunks if over limit
+ for sb.totalLen > sb.maxBytes && len(sb.chunks) > 0 {
+ sb.totalLen -= len(sb.chunks[0].Data)
+ sb.chunks = sb.chunks[1:]
+ }
+
+ // Copy subscribers to avoid holding lock during send
+ subs := make([]chan OutputChunk, 0, len(sb.subs))
+ for ch := range sb.subs {
+ subs = append(subs, ch)
+ }
+ sb.mu.Unlock()
+
+ // Fan out to subscribers (non-blocking)
+ for _, ch := range subs {
+ select {
+ case ch <- chunk:
+ default:
+ // Subscriber is slow, drop the chunk
+ }
+ }
+}
+
+// Snapshot returns all buffered chunks for replay.
+func (sb *ScrollbackBuffer) Snapshot() []OutputChunk {
+ sb.mu.Lock()
+ defer sb.mu.Unlock()
+
+ result := make([]OutputChunk, len(sb.chunks))
+ copy(result, sb.chunks)
+ return result
+}
+
+// Subscribe returns a channel that receives live output chunks.
+func (sb *ScrollbackBuffer) Subscribe() chan OutputChunk {
+ ch := make(chan OutputChunk, 256)
+ sb.mu.Lock()
+ sb.subs[ch] = struct{}{}
+ sb.mu.Unlock()
+ return ch
+}
+
+// Unsubscribe removes a subscriber channel.
+func (sb *ScrollbackBuffer) Unsubscribe(ch chan OutputChunk) {
+ sb.mu.Lock()
+ delete(sb.subs, ch)
+ sb.mu.Unlock()
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 73355055..442c424a 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -27,26 +27,28 @@ import (
// GRPCServer implements the SandboxWorker gRPC service for control plane communication.
type GRPCServer struct {
pb.UnimplementedSandboxWorkerServer
- manager sandbox.Manager
- router *sandbox.SandboxRouter
- ptyManager *sandbox.PTYManager
- sandboxDBs *sandbox.SandboxDBManager
- checkpointStore *storage.CheckpointStore
- builder *template.Builder
- store *db.Store // nil if no DB configured
- server *grpc.Server
+ manager sandbox.Manager
+ router *sandbox.SandboxRouter
+ ptyManager *sandbox.PTYManager
+ execSessionManager *sandbox.ExecSessionManager
+ sandboxDBs *sandbox.SandboxDBManager
+ checkpointStore *storage.CheckpointStore
+ builder *template.Builder
+ store *db.Store // nil if no DB configured
+ server *grpc.Server
}
// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
-func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {
+func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {
s := &GRPCServer{
- manager: mgr,
- router: router,
- ptyManager: ptyMgr,
- sandboxDBs: sandboxDBs,
- checkpointStore: checkpointStore,
- builder: builder,
- store: store,
+ manager: mgr,
+ router: router,
+ ptyManager: ptyMgr,
+ execSessionManager: execMgr,
+ sandboxDBs: sandboxDBs,
+ checkpointStore: checkpointStore,
+ builder: builder,
+ store: store,
server: grpc.NewServer(
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 5 * time.Second,
@@ -345,6 +347,93 @@ func (s *GRPCServer) PTYStream(_ pb.SandboxWorker_PTYStreamServer) error {
return fmt.Errorf("PTY streaming not implemented via gRPC, use WebSocket API directly")
}
+func (s *GRPCServer) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreateRequest) (*pb.ExecSessionCreateResponse, error) {
+ if s.execSessionManager == nil {
+ return nil, fmt.Errorf("exec sessions not configured on this worker")
+ }
+
+ createReq := types.ExecSessionCreateRequest{
+ Command: req.Command,
+ Args: req.Args,
+ Env: req.Envs,
+ Cwd: req.Cwd,
+ Timeout: int(req.TimeoutSeconds),
+ MaxRunAfterDisconnect: int(req.MaxRunAfterDisconnect),
+ }
+
+ var session *sandbox.ExecSessionHandle
+
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.execSessionManager.CreateSession(req.SandboxId, createReq)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "execSessionCreate", routeOp); err != nil {
+ return nil, fmt.Errorf("exec session create failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("exec session create failed: %w", err)
+ }
+ }
+
+ return &pb.ExecSessionCreateResponse{SessionId: session.ID}, nil
+}
+
+func (s *GRPCServer) ExecSessionList(ctx context.Context, req *pb.ExecSessionListRequest) (*pb.ExecSessionListResponse, error) {
+ if s.execSessionManager == nil {
+ return nil, fmt.Errorf("exec sessions not configured on this worker")
+ }
+
+ sessions := s.execSessionManager.ListSessions(req.SandboxId)
+
+ var entries []*pb.ExecSessionInfoEntry
+ for _, si := range sessions {
+ entry := &pb.ExecSessionInfoEntry{
+ SessionId: si.SessionID,
+ Command: si.Command,
+ Args: si.Args,
+ Running: si.Running,
+ StartedAt: 0,
+ }
+ if si.ExitCode != nil {
+ entry.ExitCode = int32(*si.ExitCode)
+ }
+ entries = append(entries, entry)
+ }
+
+ return &pb.ExecSessionListResponse{Sessions: entries}, nil
+}
+
+func (s *GRPCServer) ExecSessionKill(ctx context.Context, req *pb.ExecSessionKillRequest) (*pb.ExecSessionKillResponse, error) {
+ if s.execSessionManager == nil {
+ return nil, fmt.Errorf("exec sessions not configured on this worker")
+ }
+
+ signal := int(req.Signal)
+ if signal == 0 {
+ signal = 9
+ }
+
+ routeOp := func(_ context.Context) error {
+ return s.execSessionManager.KillSession(req.SessionId, signal)
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "execSessionKill", routeOp); err != nil {
+ return nil, fmt.Errorf("exec session kill failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("exec session kill failed: %w", err)
+ }
+ }
+
+ return &pb.ExecSessionKillResponse{}, nil
+}
+
func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSandboxRequest) (*pb.HibernateSandboxResponse, error) {
if s.checkpointStore == nil {
return nil, fmt.Errorf("hibernation not configured on this worker")
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index e5bc8315..b2fac43c 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -2,6 +2,7 @@ package worker
import (
"context"
+ "encoding/binary"
"io"
"net/http"
"time"
@@ -58,28 +59,31 @@ func (s *HTTPServer) getSandbox(c echo.Context) error {
return c.JSON(http.StatusOK, sb)
}
-func (s *HTTPServer) runCommand(c echo.Context) error {
+func (s *HTTPServer) createExecSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
id := c.Param("id")
- var cfg types.ProcessConfig
- if err := c.Bind(&cfg); err != nil {
+ var req types.ExecSessionCreateRequest
+ if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
}
- if cfg.Command == "" {
+ if req.Command == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
}
- var result *types.ProcessResult
- var execErr error
- start := time.Now()
+ var session *sandbox.ExecSessionHandle
- routeOp := func(ctx context.Context) error {
- result, execErr = s.manager.Exec(ctx, id, cfg)
- return execErr
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.execSessionManager.CreateSession(id, req)
+ return err
}
if s.router != nil {
- if err := s.router.Route(c.Request().Context(), id, "exec", routeOp); err != nil {
+ if err := s.router.Route(c.Request().Context(), id, "execSessionCreate", routeOp); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
} else {
@@ -88,17 +92,184 @@ func (s *HTTPServer) runCommand(c echo.Context) error {
}
}
- durationMs := int(time.Since(start).Milliseconds())
+ return c.JSON(http.StatusCreated, types.ExecSessionInfo{
+ SessionID: session.ID,
+ SandboxID: id,
+ Command: session.Command,
+ Args: session.Args,
+ Running: true,
+ StartedAt: session.StartedAt.Format(time.RFC3339),
+ })
+}
- // Log command to per-sandbox SQLite
- if s.sandboxDBs != nil {
- sdb, dbErr := s.sandboxDBs.Get(id)
- if dbErr == nil {
- _ = sdb.LogCommand(cfg.Command, cfg.Args, cfg.Cwd, result.ExitCode, durationMs, len(result.Stdout), len(result.Stderr))
+func (s *HTTPServer) listExecSessions(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
+ id := c.Param("id")
+ sessions := s.execSessionManager.ListSessions(id)
+
+ if sessions == nil {
+ sessions = []types.ExecSessionInfo{}
+ }
+
+ return c.JSON(http.StatusOK, sessions)
+}
+
+func (s *HTTPServer) execSessionWebSocket(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
+ id := c.Param("id")
+ sessionID := c.Param("sessionID")
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+
+ ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
+ if err != nil {
+ return err
+ }
+ defer ws.Close()
+
+ if session.Scrollback == nil {
+ ws.WriteControl(websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, "no scrollback"),
+ time.Now().Add(time.Second))
+ return nil
+ }
+
+ // Send scrollback snapshot
+ snapshot := session.Scrollback.Snapshot()
+ for _, chunk := range snapshot {
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream
+ copy(msg[1:], chunk.Data)
+ if err := ws.WriteMessage(websocket.BinaryMessage, msg); err != nil {
+ return nil
+ }
+ }
+
+ // Send scrollback_end marker (0x04)
+ if err := ws.WriteMessage(websocket.BinaryMessage, []byte{0x04}); err != nil {
+ return nil
+ }
+
+ // Subscribe for live output
+ sub := session.Scrollback.Subscribe()
+ defer session.Scrollback.Unsubscribe(sub)
+
+ // Read stdin from WebSocket
+ wsDone := make(chan struct{})
+ go func() {
+ defer close(wsDone)
+ for {
+ _, raw, err := ws.ReadMessage()
+ if err != nil {
+ return
+ }
+ if len(raw) < 1 {
+ continue
+ }
+ if raw[0] == 0x00 && len(raw) > 1 && session.StdinWriter != nil {
+ session.StdinWriter.Write(raw[1:])
+ }
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+ }
+ }()
+
+ for {
+ select {
+ case chunk, ok := <-sub:
+ if !ok {
+ return nil
+ }
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream
+ copy(msg[1:], chunk.Data)
+ if err := ws.WriteMessage(websocket.BinaryMessage, msg); err != nil {
+ return nil
+ }
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+
+ case <-session.Done:
+ // Drain remaining
+ for {
+ select {
+ case chunk := <-sub:
+ msg := make([]byte, 1+len(chunk.Data))
+ msg[0] = chunk.Stream
+ copy(msg[1:], chunk.Data)
+ _ = ws.WriteMessage(websocket.BinaryMessage, msg)
+ default:
+ goto sendExit
+ }
+ }
+ sendExit:
+ exitMsg := make([]byte, 5)
+ exitMsg[0] = 0x03
+ exitCode := 0
+ if session.ExitCode != nil {
+ exitCode = *session.ExitCode
+ }
+ binary.BigEndian.PutUint32(exitMsg[1:], uint32(int32(exitCode)))
+ _ = ws.WriteMessage(websocket.BinaryMessage, exitMsg)
+
+ ws.WriteControl(websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
+ time.Now().Add(time.Second))
+ return nil
+
+ case <-wsDone:
+ return nil
}
}
+}
+
+func (s *HTTPServer) killExecSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
+ id := c.Param("id")
+ sessionID := c.Param("sessionID")
+
+ var body struct {
+ Signal int `json:"signal"`
+ }
+ _ = c.Bind(&body)
- return c.JSON(http.StatusOK, result)
+ if body.Signal == 0 {
+ body.Signal = 9
+ }
+
+ routeOp := func(_ context.Context) error {
+ return s.execSessionManager.KillSession(sessionID, body.Signal)
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "execSessionKill", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ }
+
+ return c.NoContent(http.StatusNoContent)
}
func (s *HTTPServer) readFile(c echo.Context) error {
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index 0db0184f..19ea1b9a 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -14,29 +14,31 @@ import (
// HTTPServer serves the REST/WebSocket API for direct SDK access on the worker.
// It exposes the same endpoints as the control plane but authenticates via sandbox-scoped JWTs.
type HTTPServer struct {
- echo *echo.Echo
- manager sandbox.Manager
- ptyManager *sandbox.PTYManager
- jwtIssuer *auth.JWTIssuer
- sandboxDBs *sandbox.SandboxDBManager
- router *sandbox.SandboxRouter
- sandboxDomain string
+ echo *echo.Echo
+ manager sandbox.Manager
+ ptyManager *sandbox.PTYManager
+ execSessionManager *sandbox.ExecSessionManager
+ jwtIssuer *auth.JWTIssuer
+ sandboxDBs *sandbox.SandboxDBManager
+ router *sandbox.SandboxRouter
+ sandboxDomain string
}
// NewHTTPServer creates a new worker HTTP server for direct SDK access.
-func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {
+func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {
e := echo.New()
e.HideBanner = true
e.HidePort = true
s := &HTTPServer{
- echo: e,
- manager: mgr,
- ptyManager: ptyMgr,
- jwtIssuer: jwtIssuer,
- sandboxDBs: sandboxDBs,
- router: sbRouter,
- sandboxDomain: sandboxDomain,
+ echo: e,
+ manager: mgr,
+ ptyManager: ptyMgr,
+ execSessionManager: execMgr,
+ jwtIssuer: jwtIssuer,
+ sandboxDBs: sandboxDBs,
+ router: sbRouter,
+ sandboxDomain: sandboxDomain,
}
// Global middleware
@@ -79,8 +81,11 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *a
// Sandbox status
api.GET("/sandboxes/:id", s.getSandbox)
- // Commands
- api.POST("/sandboxes/:id/commands", s.runCommand)
+ // Exec sessions (replaces old /commands)
+ api.POST("/sandboxes/:id/exec", s.createExecSession)
+ api.GET("/sandboxes/:id/exec", s.listExecSessions)
+ api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
// Timeout
api.POST("/sandboxes/:id/timeout", s.setTimeout)
diff --git a/pkg/types/exec_session.go b/pkg/types/exec_session.go
new file mode 100644
index 00000000..3639feb7
--- /dev/null
+++ b/pkg/types/exec_session.go
@@ -0,0 +1,23 @@
+package types
+
+// ExecSessionCreateRequest is the request body for creating an exec session.
+type ExecSessionCreateRequest struct {
+ Command string `json:"cmd"`
+ Args []string `json:"args,omitempty"`
+ Env map[string]string `json:"envs,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+ MaxRunAfterDisconnect int `json:"maxRunAfterDisconnect,omitempty"`
+}
+
+// ExecSessionInfo is the response body for exec session metadata.
+type ExecSessionInfo struct {
+ SessionID string `json:"sessionID"`
+ SandboxID string `json:"sandboxID"`
+ Command string `json:"command"`
+ Args []string `json:"args"`
+ Running bool `json:"running"`
+ ExitCode *int `json:"exitCode,omitempty"`
+ StartedAt string `json:"startedAt"`
+ AttachedClients int `json:"attachedClients"`
+}
diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.go
index 170a4345..fcf8e4c2 100644
--- a/proto/agent/agent.pb.go
+++ b/proto/agent/agent.pb.go
@@ -67,6 +67,58 @@ func (ExecOutputChunk_Stream) EnumDescriptor() ([]byte, []int) {
return file_proto_agent_agent_proto_rawDescGZIP(), []int{2, 0}
}
+type ExecSessionOutput_Type int32
+
+const (
+ ExecSessionOutput_STDOUT ExecSessionOutput_Type = 0
+ ExecSessionOutput_STDERR ExecSessionOutput_Type = 1
+ ExecSessionOutput_EXIT ExecSessionOutput_Type = 2
+ ExecSessionOutput_SCROLLBACK_END ExecSessionOutput_Type = 3
+)
+
+// Enum value maps for ExecSessionOutput_Type.
+var (
+ ExecSessionOutput_Type_name = map[int32]string{
+ 0: "STDOUT",
+ 1: "STDERR",
+ 2: "EXIT",
+ 3: "SCROLLBACK_END",
+ }
+ ExecSessionOutput_Type_value = map[string]int32{
+ "STDOUT": 0,
+ "STDERR": 1,
+ "EXIT": 2,
+ "SCROLLBACK_END": 3,
+ }
+)
+
+func (x ExecSessionOutput_Type) Enum() *ExecSessionOutput_Type {
+ p := new(ExecSessionOutput_Type)
+ *p = x
+ return p
+}
+
+func (x ExecSessionOutput_Type) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (ExecSessionOutput_Type) Descriptor() protoreflect.EnumDescriptor {
+ return file_proto_agent_agent_proto_enumTypes[1].Descriptor()
+}
+
+func (ExecSessionOutput_Type) Type() protoreflect.EnumType {
+ return &file_proto_agent_agent_proto_enumTypes[1]
+}
+
+func (x ExecSessionOutput_Type) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use ExecSessionOutput_Type.Descriptor instead.
+func (ExecSessionOutput_Type) EnumDescriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{31, 0}
+}
+
type ExecRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
@@ -1467,6 +1519,514 @@ func (*PTYKillResponse) Descriptor() ([]byte, []int) {
return file_proto_agent_agent_proto_rawDescGZIP(), []int{27}
}
+type ExecSessionCreateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,2,rep,name=args,proto3" json:"args,omitempty"`
+ Envs map[string]string `protobuf:"bytes,3,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Cwd string `protobuf:"bytes,4,opt,name=cwd,proto3" json:"cwd,omitempty"`
+ TimeoutSeconds int32 `protobuf:"varint,5,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // 0 = no timeout (run until exit/kill)
+ MaxRunAfterDisconnect int32 `protobuf:"varint,6,opt,name=max_run_after_disconnect,json=maxRunAfterDisconnect,proto3" json:"max_run_after_disconnect,omitempty"` // seconds, 0 = run forever
+ ScrollbackMaxBytes int32 `protobuf:"varint,7,opt,name=scrollback_max_bytes,json=scrollbackMaxBytes,proto3" json:"scrollback_max_bytes,omitempty"` // 0 = default (1MB)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionCreateRequest) Reset() {
+ *x = ExecSessionCreateRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[28]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionCreateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionCreateRequest) ProtoMessage() {}
+
+func (x *ExecSessionCreateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[28]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionCreateRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionCreateRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{28}
+}
+
+func (x *ExecSessionCreateRequest) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecSessionCreateRequest) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecSessionCreateRequest) GetEnvs() map[string]string {
+ if x != nil {
+ return x.Envs
+ }
+ return nil
+}
+
+func (x *ExecSessionCreateRequest) GetCwd() string {
+ if x != nil {
+ return x.Cwd
+ }
+ return ""
+}
+
+func (x *ExecSessionCreateRequest) GetTimeoutSeconds() int32 {
+ if x != nil {
+ return x.TimeoutSeconds
+ }
+ return 0
+}
+
+func (x *ExecSessionCreateRequest) GetMaxRunAfterDisconnect() int32 {
+ if x != nil {
+ return x.MaxRunAfterDisconnect
+ }
+ return 0
+}
+
+func (x *ExecSessionCreateRequest) GetScrollbackMaxBytes() int32 {
+ if x != nil {
+ return x.ScrollbackMaxBytes
+ }
+ return 0
+}
+
+type ExecSessionCreateResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionCreateResponse) Reset() {
+ *x = ExecSessionCreateResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[29]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionCreateResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionCreateResponse) ProtoMessage() {}
+
+func (x *ExecSessionCreateResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[29]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionCreateResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionCreateResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{29}
+}
+
+func (x *ExecSessionCreateResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+type ExecSessionInput struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` // required on first message
+ Stdin []byte `protobuf:"bytes,2,opt,name=stdin,proto3" json:"stdin,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionInput) Reset() {
+ *x = ExecSessionInput{}
+ mi := &file_proto_agent_agent_proto_msgTypes[30]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionInput) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionInput) ProtoMessage() {}
+
+func (x *ExecSessionInput) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[30]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionInput.ProtoReflect.Descriptor instead.
+func (*ExecSessionInput) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{30}
+}
+
+func (x *ExecSessionInput) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *ExecSessionInput) GetStdin() []byte {
+ if x != nil {
+ return x.Stdin
+ }
+ return nil
+}
+
+type ExecSessionOutput struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Type ExecSessionOutput_Type `protobuf:"varint,1,opt,name=type,proto3,enum=agent.ExecSessionOutput_Type" json:"type,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ ExitCode int32 `protobuf:"varint,3,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"` // only set when type = EXIT
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionOutput) Reset() {
+ *x = ExecSessionOutput{}
+ mi := &file_proto_agent_agent_proto_msgTypes[31]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionOutput) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionOutput) ProtoMessage() {}
+
+func (x *ExecSessionOutput) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[31]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionOutput.ProtoReflect.Descriptor instead.
+func (*ExecSessionOutput) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{31}
+}
+
+func (x *ExecSessionOutput) GetType() ExecSessionOutput_Type {
+ if x != nil {
+ return x.Type
+ }
+ return ExecSessionOutput_STDOUT
+}
+
+func (x *ExecSessionOutput) GetData() []byte {
+ if x != nil {
+ return x.Data
+ }
+ return nil
+}
+
+func (x *ExecSessionOutput) GetExitCode() int32 {
+ if x != nil {
+ return x.ExitCode
+ }
+ return 0
+}
+
+type ExecSessionListRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionListRequest) Reset() {
+ *x = ExecSessionListRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[32]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionListRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionListRequest) ProtoMessage() {}
+
+func (x *ExecSessionListRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[32]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionListRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionListRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{32}
+}
+
+type ExecSessionListResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Sessions []*ExecSessionInfo `protobuf:"bytes,1,rep,name=sessions,proto3" json:"sessions,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionListResponse) Reset() {
+ *x = ExecSessionListResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[33]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionListResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionListResponse) ProtoMessage() {}
+
+func (x *ExecSessionListResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[33]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionListResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionListResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{33}
+}
+
+func (x *ExecSessionListResponse) GetSessions() []*ExecSessionInfo {
+ if x != nil {
+ return x.Sessions
+ }
+ return nil
+}
+
+type ExecSessionInfo struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Command string `protobuf:"bytes,2,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,3,rep,name=args,proto3" json:"args,omitempty"`
+ Running bool `protobuf:"varint,4,opt,name=running,proto3" json:"running,omitempty"`
+ ExitCode int32 `protobuf:"varint,5,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+ StartedAt int64 `protobuf:"varint,6,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"`
+ AttachedClients int32 `protobuf:"varint,7,opt,name=attached_clients,json=attachedClients,proto3" json:"attached_clients,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionInfo) Reset() {
+ *x = ExecSessionInfo{}
+ mi := &file_proto_agent_agent_proto_msgTypes[34]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionInfo) ProtoMessage() {}
+
+func (x *ExecSessionInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[34]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionInfo.ProtoReflect.Descriptor instead.
+func (*ExecSessionInfo) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{34}
+}
+
+func (x *ExecSessionInfo) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *ExecSessionInfo) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecSessionInfo) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecSessionInfo) GetRunning() bool {
+ if x != nil {
+ return x.Running
+ }
+ return false
+}
+
+func (x *ExecSessionInfo) GetExitCode() int32 {
+ if x != nil {
+ return x.ExitCode
+ }
+ return 0
+}
+
+func (x *ExecSessionInfo) GetStartedAt() int64 {
+ if x != nil {
+ return x.StartedAt
+ }
+ return 0
+}
+
+func (x *ExecSessionInfo) GetAttachedClients() int32 {
+ if x != nil {
+ return x.AttachedClients
+ }
+ return 0
+}
+
+type ExecSessionKillRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Signal int32 `protobuf:"varint,2,opt,name=signal,proto3" json:"signal,omitempty"` // 0 = SIGKILL
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionKillRequest) Reset() {
+ *x = ExecSessionKillRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[35]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionKillRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionKillRequest) ProtoMessage() {}
+
+func (x *ExecSessionKillRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[35]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionKillRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionKillRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{35}
+}
+
+func (x *ExecSessionKillRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *ExecSessionKillRequest) GetSignal() int32 {
+ if x != nil {
+ return x.Signal
+ }
+ return 0
+}
+
+type ExecSessionKillResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionKillResponse) Reset() {
+ *x = ExecSessionKillResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[36]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionKillResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionKillResponse) ProtoMessage() {}
+
+func (x *ExecSessionKillResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[36]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionKillResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionKillResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{36}
+}
+
type SetEnvsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Envs map[string]string `protobuf:"bytes,1,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
@@ -1476,7 +2036,7 @@ type SetEnvsRequest struct {
func (x *SetEnvsRequest) Reset() {
*x = SetEnvsRequest{}
- mi := &file_proto_agent_agent_proto_msgTypes[28]
+ mi := &file_proto_agent_agent_proto_msgTypes[37]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1488,7 +2048,7 @@ func (x *SetEnvsRequest) String() string {
func (*SetEnvsRequest) ProtoMessage() {}
func (x *SetEnvsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[28]
+ mi := &file_proto_agent_agent_proto_msgTypes[37]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1501,7 +2061,7 @@ func (x *SetEnvsRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use SetEnvsRequest.ProtoReflect.Descriptor instead.
func (*SetEnvsRequest) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{28}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{37}
}
func (x *SetEnvsRequest) GetEnvs() map[string]string {
@@ -1519,7 +2079,7 @@ type SetEnvsResponse struct {
func (x *SetEnvsResponse) Reset() {
*x = SetEnvsResponse{}
- mi := &file_proto_agent_agent_proto_msgTypes[29]
+ mi := &file_proto_agent_agent_proto_msgTypes[38]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1531,7 +2091,7 @@ func (x *SetEnvsResponse) String() string {
func (*SetEnvsResponse) ProtoMessage() {}
func (x *SetEnvsResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[29]
+ mi := &file_proto_agent_agent_proto_msgTypes[38]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1544,7 +2104,7 @@ func (x *SetEnvsResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use SetEnvsResponse.ProtoReflect.Descriptor instead.
func (*SetEnvsResponse) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{29}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{38}
}
type ShutdownRequest struct {
@@ -1555,7 +2115,7 @@ type ShutdownRequest struct {
func (x *ShutdownRequest) Reset() {
*x = ShutdownRequest{}
- mi := &file_proto_agent_agent_proto_msgTypes[30]
+ mi := &file_proto_agent_agent_proto_msgTypes[39]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1567,7 +2127,7 @@ func (x *ShutdownRequest) String() string {
func (*ShutdownRequest) ProtoMessage() {}
func (x *ShutdownRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[30]
+ mi := &file_proto_agent_agent_proto_msgTypes[39]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1580,7 +2140,7 @@ func (x *ShutdownRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use ShutdownRequest.ProtoReflect.Descriptor instead.
func (*ShutdownRequest) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{30}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{39}
}
type ShutdownResponse struct {
@@ -1591,7 +2151,7 @@ type ShutdownResponse struct {
func (x *ShutdownResponse) Reset() {
*x = ShutdownResponse{}
- mi := &file_proto_agent_agent_proto_msgTypes[31]
+ mi := &file_proto_agent_agent_proto_msgTypes[40]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1603,7 +2163,7 @@ func (x *ShutdownResponse) String() string {
func (*ShutdownResponse) ProtoMessage() {}
func (x *ShutdownResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[31]
+ mi := &file_proto_agent_agent_proto_msgTypes[40]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1616,7 +2176,7 @@ func (x *ShutdownResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use ShutdownResponse.ProtoReflect.Descriptor instead.
func (*ShutdownResponse) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{31}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{40}
}
type SyncFSRequest struct {
@@ -1627,7 +2187,7 @@ type SyncFSRequest struct {
func (x *SyncFSRequest) Reset() {
*x = SyncFSRequest{}
- mi := &file_proto_agent_agent_proto_msgTypes[32]
+ mi := &file_proto_agent_agent_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1639,7 +2199,7 @@ func (x *SyncFSRequest) String() string {
func (*SyncFSRequest) ProtoMessage() {}
func (x *SyncFSRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[32]
+ mi := &file_proto_agent_agent_proto_msgTypes[41]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1652,7 +2212,7 @@ func (x *SyncFSRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use SyncFSRequest.ProtoReflect.Descriptor instead.
func (*SyncFSRequest) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{32}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{41}
}
type SyncFSResponse struct {
@@ -1663,7 +2223,7 @@ type SyncFSResponse struct {
func (x *SyncFSResponse) Reset() {
*x = SyncFSResponse{}
- mi := &file_proto_agent_agent_proto_msgTypes[33]
+ mi := &file_proto_agent_agent_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1675,7 +2235,7 @@ func (x *SyncFSResponse) String() string {
func (*SyncFSResponse) ProtoMessage() {}
func (x *SyncFSResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_agent_agent_proto_msgTypes[33]
+ mi := &file_proto_agent_agent_proto_msgTypes[42]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1688,7 +2248,7 @@ func (x *SyncFSResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use SyncFSResponse.ProtoReflect.Descriptor instead.
func (*SyncFSResponse) Descriptor() ([]byte, []int) {
- return file_proto_agent_agent_proto_rawDescGZIP(), []int{33}
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{42}
}
var File_proto_agent_agent_proto protoreflect.FileDescriptor
@@ -1785,7 +2345,54 @@ const file_proto_agent_agent_proto_rawDesc = "" +
"\x0ePTYKillRequest\x12\x1d\n" +
"\n" +
"session_id\x18\x01 \x01(\tR\tsessionId\"\x11\n" +
- "\x0fPTYKillResponse\"~\n" +
+ "\x0fPTYKillResponse\"\xe6\x02\n" +
+ "\x18ExecSessionCreateRequest\x12\x18\n" +
+ "\acommand\x18\x01 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x02 \x03(\tR\x04args\x12=\n" +
+ "\x04envs\x18\x03 \x03(\v2).agent.ExecSessionCreateRequest.EnvsEntryR\x04envs\x12\x10\n" +
+ "\x03cwd\x18\x04 \x01(\tR\x03cwd\x12'\n" +
+ "\x0ftimeout_seconds\x18\x05 \x01(\x05R\x0etimeoutSeconds\x127\n" +
+ "\x18max_run_after_disconnect\x18\x06 \x01(\x05R\x15maxRunAfterDisconnect\x120\n" +
+ "\x14scrollback_max_bytes\x18\a \x01(\x05R\x12scrollbackMaxBytes\x1a7\n" +
+ "\tEnvsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\":\n" +
+ "\x19ExecSessionCreateResponse\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\"G\n" +
+ "\x10ExecSessionInput\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x14\n" +
+ "\x05stdin\x18\x02 \x01(\fR\x05stdin\"\xb5\x01\n" +
+ "\x11ExecSessionOutput\x121\n" +
+ "\x04type\x18\x01 \x01(\x0e2\x1d.agent.ExecSessionOutput.TypeR\x04type\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\x12\x1b\n" +
+ "\texit_code\x18\x03 \x01(\x05R\bexitCode\"<\n" +
+ "\x04Type\x12\n" +
+ "\n" +
+ "\x06STDOUT\x10\x00\x12\n" +
+ "\n" +
+ "\x06STDERR\x10\x01\x12\b\n" +
+ "\x04EXIT\x10\x02\x12\x12\n" +
+ "\x0eSCROLLBACK_END\x10\x03\"\x18\n" +
+ "\x16ExecSessionListRequest\"M\n" +
+ "\x17ExecSessionListResponse\x122\n" +
+ "\bsessions\x18\x01 \x03(\v2\x16.agent.ExecSessionInfoR\bsessions\"\xdf\x01\n" +
+ "\x0fExecSessionInfo\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x18\n" +
+ "\acommand\x18\x02 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x03 \x03(\tR\x04args\x12\x18\n" +
+ "\arunning\x18\x04 \x01(\bR\arunning\x12\x1b\n" +
+ "\texit_code\x18\x05 \x01(\x05R\bexitCode\x12\x1d\n" +
+ "\n" +
+ "started_at\x18\x06 \x01(\x03R\tstartedAt\x12)\n" +
+ "\x10attached_clients\x18\a \x01(\x05R\x0fattachedClients\"O\n" +
+ "\x16ExecSessionKillRequest\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x16\n" +
+ "\x06signal\x18\x02 \x01(\x05R\x06signal\"\x19\n" +
+ "\x17ExecSessionKillResponse\"~\n" +
"\x0eSetEnvsRequest\x123\n" +
"\x04envs\x18\x01 \x03(\v2\x1f.agent.SetEnvsRequest.EnvsEntryR\x04envs\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
@@ -1795,7 +2402,8 @@ const file_proto_agent_agent_proto_rawDesc = "" +
"\x0fShutdownRequest\"\x12\n" +
"\x10ShutdownResponse\"\x0f\n" +
"\rSyncFSRequest\"\x10\n" +
- "\x0eSyncFSResponse2\xd8\a\n" +
+ "\x0eSyncFSResponse2\xa0\n" +
+ "\n" +
"\fSandboxAgent\x12/\n" +
"\x04Exec\x12\x12.agent.ExecRequest\x1a\x13.agent.ExecResponse\x12:\n" +
"\n" +
@@ -1811,7 +2419,11 @@ const file_proto_agent_agent_proto_rawDesc = "" +
"\x04Ping\x12\x12.agent.PingRequest\x1a\x13.agent.PingResponse\x12>\n" +
"\tPTYCreate\x12\x17.agent.PTYCreateRequest\x1a\x18.agent.PTYCreateResponse\x12>\n" +
"\tPTYResize\x12\x17.agent.PTYResizeRequest\x1a\x18.agent.PTYResizeResponse\x128\n" +
- "\aPTYKill\x12\x15.agent.PTYKillRequest\x1a\x16.agent.PTYKillResponse\x128\n" +
+ "\aPTYKill\x12\x15.agent.PTYKillRequest\x1a\x16.agent.PTYKillResponse\x12V\n" +
+ "\x11ExecSessionCreate\x12\x1f.agent.ExecSessionCreateRequest\x1a .agent.ExecSessionCreateResponse\x12J\n" +
+ "\x11ExecSessionAttach\x12\x17.agent.ExecSessionInput\x1a\x18.agent.ExecSessionOutput(\x010\x01\x12P\n" +
+ "\x0fExecSessionList\x12\x1d.agent.ExecSessionListRequest\x1a\x1e.agent.ExecSessionListResponse\x12P\n" +
+ "\x0fExecSessionKill\x12\x1d.agent.ExecSessionKillRequest\x1a\x1e.agent.ExecSessionKillResponse\x128\n" +
"\aSetEnvs\x12\x15.agent.SetEnvsRequest\x1a\x16.agent.SetEnvsResponse\x12;\n" +
"\bShutdown\x12\x16.agent.ShutdownRequest\x1a\x17.agent.ShutdownResponse\x125\n" +
"\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"
@@ -1828,91 +2440,113 @@ func file_proto_agent_agent_proto_rawDescGZIP() []byte {
return file_proto_agent_agent_proto_rawDescData
}
-var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 36)
+var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
+var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 46)
var file_proto_agent_agent_proto_goTypes = []any{
- (ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream
- (*ExecRequest)(nil), // 1: agent.ExecRequest
- (*ExecResponse)(nil), // 2: agent.ExecResponse
- (*ExecOutputChunk)(nil), // 3: agent.ExecOutputChunk
- (*ReadFileRequest)(nil), // 4: agent.ReadFileRequest
- (*ReadFileResponse)(nil), // 5: agent.ReadFileResponse
- (*WriteFileRequest)(nil), // 6: agent.WriteFileRequest
- (*WriteFileResponse)(nil), // 7: agent.WriteFileResponse
- (*ListDirRequest)(nil), // 8: agent.ListDirRequest
- (*DirEntry)(nil), // 9: agent.DirEntry
- (*ListDirResponse)(nil), // 10: agent.ListDirResponse
- (*MakeDirRequest)(nil), // 11: agent.MakeDirRequest
- (*MakeDirResponse)(nil), // 12: agent.MakeDirResponse
- (*RemoveRequest)(nil), // 13: agent.RemoveRequest
- (*RemoveResponse)(nil), // 14: agent.RemoveResponse
- (*ExistsRequest)(nil), // 15: agent.ExistsRequest
- (*ExistsResponse)(nil), // 16: agent.ExistsResponse
- (*StatRequest)(nil), // 17: agent.StatRequest
- (*StatResponse)(nil), // 18: agent.StatResponse
- (*StatsRequest)(nil), // 19: agent.StatsRequest
- (*StatsResponse)(nil), // 20: agent.StatsResponse
- (*PingRequest)(nil), // 21: agent.PingRequest
- (*PingResponse)(nil), // 22: agent.PingResponse
- (*PTYCreateRequest)(nil), // 23: agent.PTYCreateRequest
- (*PTYCreateResponse)(nil), // 24: agent.PTYCreateResponse
- (*PTYResizeRequest)(nil), // 25: agent.PTYResizeRequest
- (*PTYResizeResponse)(nil), // 26: agent.PTYResizeResponse
- (*PTYKillRequest)(nil), // 27: agent.PTYKillRequest
- (*PTYKillResponse)(nil), // 28: agent.PTYKillResponse
- (*SetEnvsRequest)(nil), // 29: agent.SetEnvsRequest
- (*SetEnvsResponse)(nil), // 30: agent.SetEnvsResponse
- (*ShutdownRequest)(nil), // 31: agent.ShutdownRequest
- (*ShutdownResponse)(nil), // 32: agent.ShutdownResponse
- (*SyncFSRequest)(nil), // 33: agent.SyncFSRequest
- (*SyncFSResponse)(nil), // 34: agent.SyncFSResponse
- nil, // 35: agent.ExecRequest.EnvsEntry
- nil, // 36: agent.SetEnvsRequest.EnvsEntry
+ (ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream
+ (ExecSessionOutput_Type)(0), // 1: agent.ExecSessionOutput.Type
+ (*ExecRequest)(nil), // 2: agent.ExecRequest
+ (*ExecResponse)(nil), // 3: agent.ExecResponse
+ (*ExecOutputChunk)(nil), // 4: agent.ExecOutputChunk
+ (*ReadFileRequest)(nil), // 5: agent.ReadFileRequest
+ (*ReadFileResponse)(nil), // 6: agent.ReadFileResponse
+ (*WriteFileRequest)(nil), // 7: agent.WriteFileRequest
+ (*WriteFileResponse)(nil), // 8: agent.WriteFileResponse
+ (*ListDirRequest)(nil), // 9: agent.ListDirRequest
+ (*DirEntry)(nil), // 10: agent.DirEntry
+ (*ListDirResponse)(nil), // 11: agent.ListDirResponse
+ (*MakeDirRequest)(nil), // 12: agent.MakeDirRequest
+ (*MakeDirResponse)(nil), // 13: agent.MakeDirResponse
+ (*RemoveRequest)(nil), // 14: agent.RemoveRequest
+ (*RemoveResponse)(nil), // 15: agent.RemoveResponse
+ (*ExistsRequest)(nil), // 16: agent.ExistsRequest
+ (*ExistsResponse)(nil), // 17: agent.ExistsResponse
+ (*StatRequest)(nil), // 18: agent.StatRequest
+ (*StatResponse)(nil), // 19: agent.StatResponse
+ (*StatsRequest)(nil), // 20: agent.StatsRequest
+ (*StatsResponse)(nil), // 21: agent.StatsResponse
+ (*PingRequest)(nil), // 22: agent.PingRequest
+ (*PingResponse)(nil), // 23: agent.PingResponse
+ (*PTYCreateRequest)(nil), // 24: agent.PTYCreateRequest
+ (*PTYCreateResponse)(nil), // 25: agent.PTYCreateResponse
+ (*PTYResizeRequest)(nil), // 26: agent.PTYResizeRequest
+ (*PTYResizeResponse)(nil), // 27: agent.PTYResizeResponse
+ (*PTYKillRequest)(nil), // 28: agent.PTYKillRequest
+ (*PTYKillResponse)(nil), // 29: agent.PTYKillResponse
+ (*ExecSessionCreateRequest)(nil), // 30: agent.ExecSessionCreateRequest
+ (*ExecSessionCreateResponse)(nil), // 31: agent.ExecSessionCreateResponse
+ (*ExecSessionInput)(nil), // 32: agent.ExecSessionInput
+ (*ExecSessionOutput)(nil), // 33: agent.ExecSessionOutput
+ (*ExecSessionListRequest)(nil), // 34: agent.ExecSessionListRequest
+ (*ExecSessionListResponse)(nil), // 35: agent.ExecSessionListResponse
+ (*ExecSessionInfo)(nil), // 36: agent.ExecSessionInfo
+ (*ExecSessionKillRequest)(nil), // 37: agent.ExecSessionKillRequest
+ (*ExecSessionKillResponse)(nil), // 38: agent.ExecSessionKillResponse
+ (*SetEnvsRequest)(nil), // 39: agent.SetEnvsRequest
+ (*SetEnvsResponse)(nil), // 40: agent.SetEnvsResponse
+ (*ShutdownRequest)(nil), // 41: agent.ShutdownRequest
+ (*ShutdownResponse)(nil), // 42: agent.ShutdownResponse
+ (*SyncFSRequest)(nil), // 43: agent.SyncFSRequest
+ (*SyncFSResponse)(nil), // 44: agent.SyncFSResponse
+ nil, // 45: agent.ExecRequest.EnvsEntry
+ nil, // 46: agent.ExecSessionCreateRequest.EnvsEntry
+ nil, // 47: agent.SetEnvsRequest.EnvsEntry
}
var file_proto_agent_agent_proto_depIdxs = []int32{
- 35, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry
+ 45, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry
0, // 1: agent.ExecOutputChunk.stream:type_name -> agent.ExecOutputChunk.Stream
- 9, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry
- 36, // 3: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry
- 1, // 4: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest
- 1, // 5: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest
- 4, // 6: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest
- 6, // 7: agent.SandboxAgent.WriteFile:input_type -> agent.WriteFileRequest
- 8, // 8: agent.SandboxAgent.ListDir:input_type -> agent.ListDirRequest
- 11, // 9: agent.SandboxAgent.MakeDir:input_type -> agent.MakeDirRequest
- 13, // 10: agent.SandboxAgent.Remove:input_type -> agent.RemoveRequest
- 15, // 11: agent.SandboxAgent.Exists:input_type -> agent.ExistsRequest
- 17, // 12: agent.SandboxAgent.Stat:input_type -> agent.StatRequest
- 19, // 13: agent.SandboxAgent.Stats:input_type -> agent.StatsRequest
- 21, // 14: agent.SandboxAgent.Ping:input_type -> agent.PingRequest
- 23, // 15: agent.SandboxAgent.PTYCreate:input_type -> agent.PTYCreateRequest
- 25, // 16: agent.SandboxAgent.PTYResize:input_type -> agent.PTYResizeRequest
- 27, // 17: agent.SandboxAgent.PTYKill:input_type -> agent.PTYKillRequest
- 29, // 18: agent.SandboxAgent.SetEnvs:input_type -> agent.SetEnvsRequest
- 31, // 19: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest
- 33, // 20: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest
- 2, // 21: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse
- 3, // 22: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk
- 5, // 23: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse
- 7, // 24: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse
- 10, // 25: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse
- 12, // 26: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse
- 14, // 27: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse
- 16, // 28: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse
- 18, // 29: agent.SandboxAgent.Stat:output_type -> agent.StatResponse
- 20, // 30: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse
- 22, // 31: agent.SandboxAgent.Ping:output_type -> agent.PingResponse
- 24, // 32: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse
- 26, // 33: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse
- 28, // 34: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse
- 30, // 35: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse
- 32, // 36: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse
- 34, // 37: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse
- 21, // [21:38] is the sub-list for method output_type
- 4, // [4:21] is the sub-list for method input_type
- 4, // [4:4] is the sub-list for extension type_name
- 4, // [4:4] is the sub-list for extension extendee
- 0, // [0:4] is the sub-list for field type_name
+ 10, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry
+ 46, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry
+ 1, // 4: agent.ExecSessionOutput.type:type_name -> agent.ExecSessionOutput.Type
+ 36, // 5: agent.ExecSessionListResponse.sessions:type_name -> agent.ExecSessionInfo
+ 47, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry
+ 2, // 7: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest
+ 2, // 8: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest
+ 5, // 9: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest
+ 7, // 10: agent.SandboxAgent.WriteFile:input_type -> agent.WriteFileRequest
+ 9, // 11: agent.SandboxAgent.ListDir:input_type -> agent.ListDirRequest
+ 12, // 12: agent.SandboxAgent.MakeDir:input_type -> agent.MakeDirRequest
+ 14, // 13: agent.SandboxAgent.Remove:input_type -> agent.RemoveRequest
+ 16, // 14: agent.SandboxAgent.Exists:input_type -> agent.ExistsRequest
+ 18, // 15: agent.SandboxAgent.Stat:input_type -> agent.StatRequest
+ 20, // 16: agent.SandboxAgent.Stats:input_type -> agent.StatsRequest
+ 22, // 17: agent.SandboxAgent.Ping:input_type -> agent.PingRequest
+ 24, // 18: agent.SandboxAgent.PTYCreate:input_type -> agent.PTYCreateRequest
+ 26, // 19: agent.SandboxAgent.PTYResize:input_type -> agent.PTYResizeRequest
+ 28, // 20: agent.SandboxAgent.PTYKill:input_type -> agent.PTYKillRequest
+ 30, // 21: agent.SandboxAgent.ExecSessionCreate:input_type -> agent.ExecSessionCreateRequest
+ 32, // 22: agent.SandboxAgent.ExecSessionAttach:input_type -> agent.ExecSessionInput
+ 34, // 23: agent.SandboxAgent.ExecSessionList:input_type -> agent.ExecSessionListRequest
+ 37, // 24: agent.SandboxAgent.ExecSessionKill:input_type -> agent.ExecSessionKillRequest
+ 39, // 25: agent.SandboxAgent.SetEnvs:input_type -> agent.SetEnvsRequest
+ 41, // 26: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest
+ 43, // 27: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest
+ 3, // 28: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse
+ 4, // 29: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk
+ 6, // 30: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse
+ 8, // 31: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse
+ 11, // 32: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse
+ 13, // 33: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse
+ 15, // 34: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse
+ 17, // 35: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse
+ 19, // 36: agent.SandboxAgent.Stat:output_type -> agent.StatResponse
+ 21, // 37: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse
+ 23, // 38: agent.SandboxAgent.Ping:output_type -> agent.PingResponse
+ 25, // 39: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse
+ 27, // 40: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse
+ 29, // 41: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse
+ 31, // 42: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse
+ 33, // 43: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput
+ 35, // 44: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse
+ 38, // 45: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse
+ 40, // 46: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse
+ 42, // 47: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse
+ 44, // 48: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse
+ 28, // [28:49] is the sub-list for method output_type
+ 7, // [7:28] is the sub-list for method input_type
+ 7, // [7:7] is the sub-list for extension type_name
+ 7, // [7:7] is the sub-list for extension extendee
+ 0, // [0:7] is the sub-list for field type_name
}
func init() { file_proto_agent_agent_proto_init() }
@@ -1925,8 +2559,8 @@ func file_proto_agent_agent_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)),
- NumEnums: 1,
- NumMessages: 36,
+ NumEnums: 2,
+ NumMessages: 46,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/agent/agent.proto b/proto/agent/agent.proto
index 9b520f7e..d5cfaf65 100644
--- a/proto/agent/agent.proto
+++ b/proto/agent/agent.proto
@@ -33,6 +33,12 @@ service SandboxAgent {
rpc PTYResize(PTYResizeRequest) returns (PTYResizeResponse);
rpc PTYKill(PTYKillRequest) returns (PTYKillResponse);
+ // Exec sessions — persistent command execution with scrollback and reconnect.
+ rpc ExecSessionCreate(ExecSessionCreateRequest) returns (ExecSessionCreateResponse);
+ rpc ExecSessionAttach(stream ExecSessionInput) returns (stream ExecSessionOutput);
+ rpc ExecSessionList(ExecSessionListRequest) returns (ExecSessionListResponse);
+ rpc ExecSessionKill(ExecSessionKillRequest) returns (ExecSessionKillResponse);
+
// SetEnvs stores sandbox-level environment variables inside the agent.
// These are injected into every subsequent Exec/ExecStream call,
// between the base OS env and per-command envs.
@@ -186,6 +192,60 @@ message PTYKillRequest {
message PTYKillResponse {}
+// --- Exec Sessions ---
+
+message ExecSessionCreateRequest {
+ string command = 1;
+ repeated string args = 2;
+ map<string, string> envs = 3;
+ string cwd = 4;
+ int32 timeout_seconds = 5; // 0 = no timeout (run until exit/kill)
+ int32 max_run_after_disconnect = 6; // seconds, 0 = run forever
+ int32 scrollback_max_bytes = 7; // 0 = default (1MB)
+}
+
+message ExecSessionCreateResponse {
+ string session_id = 1;
+}
+
+message ExecSessionInput {
+ string session_id = 1; // required on first message
+ bytes stdin = 2;
+}
+
+message ExecSessionOutput {
+ enum Type {
+ STDOUT = 0;
+ STDERR = 1;
+ EXIT = 2;
+ SCROLLBACK_END = 3;
+ }
+ Type type = 1;
+ bytes data = 2;
+ int32 exit_code = 3; // only set when type = EXIT
+}
+
+message ExecSessionListRequest {}
+message ExecSessionListResponse {
+ repeated ExecSessionInfo sessions = 1;
+}
+
+message ExecSessionInfo {
+ string session_id = 1;
+ string command = 2;
+ repeated string args = 3;
+ bool running = 4;
+ int32 exit_code = 5;
+ int64 started_at = 6;
+ int32 attached_clients = 7;
+}
+
+message ExecSessionKillRequest {
+ string session_id = 1;
+ int32 signal = 2; // 0 = SIGKILL
+}
+message ExecSessionKillResponse {}
+
// --- SetEnvs ---
message SetEnvsRequest {
diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.go
index a5a4fe92..088622da 100644
--- a/proto/agent/agent_grpc.pb.go
+++ b/proto/agent/agent_grpc.pb.go
@@ -19,23 +19,27 @@ import (
const _ = grpc.SupportPackageIsVersion9
const (
- SandboxAgent_Exec_FullMethodName = "/agent.SandboxAgent/Exec"
- SandboxAgent_ExecStream_FullMethodName = "/agent.SandboxAgent/ExecStream"
- SandboxAgent_ReadFile_FullMethodName = "/agent.SandboxAgent/ReadFile"
- SandboxAgent_WriteFile_FullMethodName = "/agent.SandboxAgent/WriteFile"
- SandboxAgent_ListDir_FullMethodName = "/agent.SandboxAgent/ListDir"
- SandboxAgent_MakeDir_FullMethodName = "/agent.SandboxAgent/MakeDir"
- SandboxAgent_Remove_FullMethodName = "/agent.SandboxAgent/Remove"
- SandboxAgent_Exists_FullMethodName = "/agent.SandboxAgent/Exists"
- SandboxAgent_Stat_FullMethodName = "/agent.SandboxAgent/Stat"
- SandboxAgent_Stats_FullMethodName = "/agent.SandboxAgent/Stats"
- SandboxAgent_Ping_FullMethodName = "/agent.SandboxAgent/Ping"
- SandboxAgent_PTYCreate_FullMethodName = "/agent.SandboxAgent/PTYCreate"
- SandboxAgent_PTYResize_FullMethodName = "/agent.SandboxAgent/PTYResize"
- SandboxAgent_PTYKill_FullMethodName = "/agent.SandboxAgent/PTYKill"
- SandboxAgent_SetEnvs_FullMethodName = "/agent.SandboxAgent/SetEnvs"
- SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"
- SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"
+ SandboxAgent_Exec_FullMethodName = "/agent.SandboxAgent/Exec"
+ SandboxAgent_ExecStream_FullMethodName = "/agent.SandboxAgent/ExecStream"
+ SandboxAgent_ReadFile_FullMethodName = "/agent.SandboxAgent/ReadFile"
+ SandboxAgent_WriteFile_FullMethodName = "/agent.SandboxAgent/WriteFile"
+ SandboxAgent_ListDir_FullMethodName = "/agent.SandboxAgent/ListDir"
+ SandboxAgent_MakeDir_FullMethodName = "/agent.SandboxAgent/MakeDir"
+ SandboxAgent_Remove_FullMethodName = "/agent.SandboxAgent/Remove"
+ SandboxAgent_Exists_FullMethodName = "/agent.SandboxAgent/Exists"
+ SandboxAgent_Stat_FullMethodName = "/agent.SandboxAgent/Stat"
+ SandboxAgent_Stats_FullMethodName = "/agent.SandboxAgent/Stats"
+ SandboxAgent_Ping_FullMethodName = "/agent.SandboxAgent/Ping"
+ SandboxAgent_PTYCreate_FullMethodName = "/agent.SandboxAgent/PTYCreate"
+ SandboxAgent_PTYResize_FullMethodName = "/agent.SandboxAgent/PTYResize"
+ SandboxAgent_PTYKill_FullMethodName = "/agent.SandboxAgent/PTYKill"
+ SandboxAgent_ExecSessionCreate_FullMethodName = "/agent.SandboxAgent/ExecSessionCreate"
+ SandboxAgent_ExecSessionAttach_FullMethodName = "/agent.SandboxAgent/ExecSessionAttach"
+ SandboxAgent_ExecSessionList_FullMethodName = "/agent.SandboxAgent/ExecSessionList"
+ SandboxAgent_ExecSessionKill_FullMethodName = "/agent.SandboxAgent/ExecSessionKill"
+ SandboxAgent_SetEnvs_FullMethodName = "/agent.SandboxAgent/SetEnvs"
+ SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"
+ SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"
)
// SandboxAgentClient is the client API for SandboxAgent service.
@@ -65,6 +69,11 @@ type SandboxAgentClient interface {
PTYCreate(ctx context.Context, in *PTYCreateRequest, opts ...grpc.CallOption) (*PTYCreateResponse, error)
PTYResize(ctx context.Context, in *PTYResizeRequest, opts ...grpc.CallOption) (*PTYResizeResponse, error)
PTYKill(ctx context.Context, in *PTYKillRequest, opts ...grpc.CallOption) (*PTYKillResponse, error)
+ // Exec sessions — persistent command execution with scrollback and reconnect.
+ ExecSessionCreate(ctx context.Context, in *ExecSessionCreateRequest, opts ...grpc.CallOption) (*ExecSessionCreateResponse, error)
+ ExecSessionAttach(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ExecSessionInput, ExecSessionOutput], error)
+ ExecSessionList(ctx context.Context, in *ExecSessionListRequest, opts ...grpc.CallOption) (*ExecSessionListResponse, error)
+ ExecSessionKill(ctx context.Context, in *ExecSessionKillRequest, opts ...grpc.CallOption) (*ExecSessionKillResponse, error)
// SetEnvs stores sandbox-level environment variables inside the agent.
// These are injected into every subsequent Exec/ExecStream call,
// between the base OS env and per-command envs.
@@ -233,6 +242,49 @@ func (c *sandboxAgentClient) PTYKill(ctx context.Context, in *PTYKillRequest, op
return out, nil
}
+func (c *sandboxAgentClient) ExecSessionCreate(ctx context.Context, in *ExecSessionCreateRequest, opts ...grpc.CallOption) (*ExecSessionCreateResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionCreateResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_ExecSessionCreate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) ExecSessionAttach(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ExecSessionInput, ExecSessionOutput], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &SandboxAgent_ServiceDesc.Streams[1], SandboxAgent_ExecSessionAttach_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[ExecSessionInput, ExecSessionOutput]{ClientStream: stream}
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxAgent_ExecSessionAttachClient = grpc.BidiStreamingClient[ExecSessionInput, ExecSessionOutput]
+
+func (c *sandboxAgentClient) ExecSessionList(ctx context.Context, in *ExecSessionListRequest, opts ...grpc.CallOption) (*ExecSessionListResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionListResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_ExecSessionList_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) ExecSessionKill(ctx context.Context, in *ExecSessionKillRequest, opts ...grpc.CallOption) (*ExecSessionKillResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionKillResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_ExecSessionKill_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *sandboxAgentClient) SetEnvs(ctx context.Context, in *SetEnvsRequest, opts ...grpc.CallOption) (*SetEnvsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetEnvsResponse)
@@ -290,6 +342,11 @@ type SandboxAgentServer interface {
PTYCreate(context.Context, *PTYCreateRequest) (*PTYCreateResponse, error)
PTYResize(context.Context, *PTYResizeRequest) (*PTYResizeResponse, error)
PTYKill(context.Context, *PTYKillRequest) (*PTYKillResponse, error)
+ // Exec sessions — persistent command execution with scrollback and reconnect.
+ ExecSessionCreate(context.Context, *ExecSessionCreateRequest) (*ExecSessionCreateResponse, error)
+ ExecSessionAttach(grpc.BidiStreamingServer[ExecSessionInput, ExecSessionOutput]) error
+ ExecSessionList(context.Context, *ExecSessionListRequest) (*ExecSessionListResponse, error)
+ ExecSessionKill(context.Context, *ExecSessionKillRequest) (*ExecSessionKillResponse, error)
// SetEnvs stores sandbox-level environment variables inside the agent.
// These are injected into every subsequent Exec/ExecStream call,
// between the base OS env and per-command envs.
@@ -351,6 +408,18 @@ func (UnimplementedSandboxAgentServer) PTYResize(context.Context, *PTYResizeRequ
func (UnimplementedSandboxAgentServer) PTYKill(context.Context, *PTYKillRequest) (*PTYKillResponse, error) {
return nil, status.Error(codes.Unimplemented, "method PTYKill not implemented")
}
+func (UnimplementedSandboxAgentServer) ExecSessionCreate(context.Context, *ExecSessionCreateRequest) (*ExecSessionCreateResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionCreate not implemented")
+}
+func (UnimplementedSandboxAgentServer) ExecSessionAttach(grpc.BidiStreamingServer[ExecSessionInput, ExecSessionOutput]) error {
+ return status.Error(codes.Unimplemented, "method ExecSessionAttach not implemented")
+}
+func (UnimplementedSandboxAgentServer) ExecSessionList(context.Context, *ExecSessionListRequest) (*ExecSessionListResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionList not implemented")
+}
+func (UnimplementedSandboxAgentServer) ExecSessionKill(context.Context, *ExecSessionKillRequest) (*ExecSessionKillResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionKill not implemented")
+}
func (UnimplementedSandboxAgentServer) SetEnvs(context.Context, *SetEnvsRequest) (*SetEnvsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetEnvs not implemented")
}
@@ -626,6 +695,67 @@ func _SandboxAgent_PTYKill_Handler(srv interface{}, ctx context.Context, dec fun
return interceptor(ctx, in, info, handler)
}
+func _SandboxAgent_ExecSessionCreate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionCreateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).ExecSessionCreate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_ExecSessionCreate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).ExecSessionCreate(ctx, req.(*ExecSessionCreateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_ExecSessionAttach_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(SandboxAgentServer).ExecSessionAttach(&grpc.GenericServerStream[ExecSessionInput, ExecSessionOutput]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxAgent_ExecSessionAttachServer = grpc.BidiStreamingServer[ExecSessionInput, ExecSessionOutput]
+
+func _SandboxAgent_ExecSessionList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionListRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).ExecSessionList(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_ExecSessionList_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).ExecSessionList(ctx, req.(*ExecSessionListRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_ExecSessionKill_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionKillRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).ExecSessionKill(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_ExecSessionKill_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).ExecSessionKill(ctx, req.(*ExecSessionKillRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _SandboxAgent_SetEnvs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetEnvsRequest)
if err := dec(in); err != nil {
@@ -739,6 +869,18 @@ var SandboxAgent_ServiceDesc = grpc.ServiceDesc{
MethodName: "PTYKill",
Handler: _SandboxAgent_PTYKill_Handler,
},
+ {
+ MethodName: "ExecSessionCreate",
+ Handler: _SandboxAgent_ExecSessionCreate_Handler,
+ },
+ {
+ MethodName: "ExecSessionList",
+ Handler: _SandboxAgent_ExecSessionList_Handler,
+ },
+ {
+ MethodName: "ExecSessionKill",
+ Handler: _SandboxAgent_ExecSessionKill_Handler,
+ },
{
MethodName: "SetEnvs",
Handler: _SandboxAgent_SetEnvs_Handler,
@@ -758,6 +900,12 @@ var SandboxAgent_ServiceDesc = grpc.ServiceDesc{
Handler: _SandboxAgent_ExecStream_Handler,
ServerStreams: true,
},
+ {
+ StreamName: "ExecSessionAttach",
+ Handler: _SandboxAgent_ExecSessionAttach_Handler,
+ ServerStreams: true,
+ ClientStreams: true,
+ },
},
Metadata: "proto/agent/agent.proto",
}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 49743318..4e096f66 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v6.33.4
+// protoc v7.34.0
// source: proto/worker/worker.proto
package worker
@@ -1832,6 +1832,418 @@ func (x *BuildTemplateResponse) GetBuildLog() string {
return ""
}
+type ExecSessionCreateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Command string `protobuf:"bytes,2,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,3,rep,name=args,proto3" json:"args,omitempty"`
+ Envs map[string]string `protobuf:"bytes,4,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Cwd string `protobuf:"bytes,5,opt,name=cwd,proto3" json:"cwd,omitempty"`
+ TimeoutSeconds int32 `protobuf:"varint,6,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"`
+ MaxRunAfterDisconnect int32 `protobuf:"varint,7,opt,name=max_run_after_disconnect,json=maxRunAfterDisconnect,proto3" json:"max_run_after_disconnect,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionCreateRequest) Reset() {
+ *x = ExecSessionCreateRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[31]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionCreateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionCreateRequest) ProtoMessage() {}
+
+func (x *ExecSessionCreateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[31]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionCreateRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionCreateRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{31}
+}
+
+func (x *ExecSessionCreateRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *ExecSessionCreateRequest) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecSessionCreateRequest) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecSessionCreateRequest) GetEnvs() map[string]string {
+ if x != nil {
+ return x.Envs
+ }
+ return nil
+}
+
+func (x *ExecSessionCreateRequest) GetCwd() string {
+ if x != nil {
+ return x.Cwd
+ }
+ return ""
+}
+
+func (x *ExecSessionCreateRequest) GetTimeoutSeconds() int32 {
+ if x != nil {
+ return x.TimeoutSeconds
+ }
+ return 0
+}
+
+func (x *ExecSessionCreateRequest) GetMaxRunAfterDisconnect() int32 {
+ if x != nil {
+ return x.MaxRunAfterDisconnect
+ }
+ return 0
+}
+
+type ExecSessionCreateResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionCreateResponse) Reset() {
+ *x = ExecSessionCreateResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[32]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionCreateResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionCreateResponse) ProtoMessage() {}
+
+func (x *ExecSessionCreateResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[32]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionCreateResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionCreateResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{32}
+}
+
+func (x *ExecSessionCreateResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+type ExecSessionListRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionListRequest) Reset() {
+ *x = ExecSessionListRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[33]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionListRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionListRequest) ProtoMessage() {}
+
+func (x *ExecSessionListRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[33]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionListRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionListRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{33}
+}
+
+func (x *ExecSessionListRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+type ExecSessionListResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Sessions []*ExecSessionInfoEntry `protobuf:"bytes,1,rep,name=sessions,proto3" json:"sessions,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionListResponse) Reset() {
+ *x = ExecSessionListResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[34]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionListResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionListResponse) ProtoMessage() {}
+
+func (x *ExecSessionListResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[34]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionListResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionListResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{34}
+}
+
+func (x *ExecSessionListResponse) GetSessions() []*ExecSessionInfoEntry {
+ if x != nil {
+ return x.Sessions
+ }
+ return nil
+}
+
+type ExecSessionInfoEntry struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Command string `protobuf:"bytes,2,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,3,rep,name=args,proto3" json:"args,omitempty"`
+ Running bool `protobuf:"varint,4,opt,name=running,proto3" json:"running,omitempty"`
+ ExitCode int32 `protobuf:"varint,5,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+ StartedAt int64 `protobuf:"varint,6,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"`
+ AttachedClients int32 `protobuf:"varint,7,opt,name=attached_clients,json=attachedClients,proto3" json:"attached_clients,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionInfoEntry) Reset() {
+ *x = ExecSessionInfoEntry{}
+ mi := &file_proto_worker_worker_proto_msgTypes[35]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionInfoEntry) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionInfoEntry) ProtoMessage() {}
+
+func (x *ExecSessionInfoEntry) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[35]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionInfoEntry.ProtoReflect.Descriptor instead.
+func (*ExecSessionInfoEntry) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{35}
+}
+
+func (x *ExecSessionInfoEntry) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *ExecSessionInfoEntry) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecSessionInfoEntry) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecSessionInfoEntry) GetRunning() bool {
+ if x != nil {
+ return x.Running
+ }
+ return false
+}
+
+func (x *ExecSessionInfoEntry) GetExitCode() int32 {
+ if x != nil {
+ return x.ExitCode
+ }
+ return 0
+}
+
+func (x *ExecSessionInfoEntry) GetStartedAt() int64 {
+ if x != nil {
+ return x.StartedAt
+ }
+ return 0
+}
+
+func (x *ExecSessionInfoEntry) GetAttachedClients() int32 {
+ if x != nil {
+ return x.AttachedClients
+ }
+ return 0
+}
+
+type ExecSessionKillRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ SessionId string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Signal int32 `protobuf:"varint,3,opt,name=signal,proto3" json:"signal,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionKillRequest) Reset() {
+ *x = ExecSessionKillRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[36]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionKillRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionKillRequest) ProtoMessage() {}
+
+func (x *ExecSessionKillRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[36]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionKillRequest.ProtoReflect.Descriptor instead.
+func (*ExecSessionKillRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{36}
+}
+
+func (x *ExecSessionKillRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *ExecSessionKillRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *ExecSessionKillRequest) GetSignal() int32 {
+ if x != nil {
+ return x.Signal
+ }
+ return 0
+}
+
+type ExecSessionKillResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecSessionKillResponse) Reset() {
+ *x = ExecSessionKillResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[37]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecSessionKillResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecSessionKillResponse) ProtoMessage() {}
+
+func (x *ExecSessionKillResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[37]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecSessionKillResponse.ProtoReflect.Descriptor instead.
+func (*ExecSessionKillResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{37}
+}
+
type GetSandboxStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -1841,7 +2253,7 @@ type GetSandboxStatsRequest struct {
func (x *GetSandboxStatsRequest) Reset() {
*x = GetSandboxStatsRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[31]
+ mi := &file_proto_worker_worker_proto_msgTypes[38]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1853,7 +2265,7 @@ func (x *GetSandboxStatsRequest) String() string {
func (*GetSandboxStatsRequest) ProtoMessage() {}
func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[31]
+ mi := &file_proto_worker_worker_proto_msgTypes[38]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1866,7 +2278,7 @@ func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetSandboxStatsRequest.ProtoReflect.Descriptor instead.
func (*GetSandboxStatsRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{31}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{38}
}
func (x *GetSandboxStatsRequest) GetSandboxId() string {
@@ -1890,7 +2302,7 @@ type GetSandboxStatsResponse struct {
func (x *GetSandboxStatsResponse) Reset() {
*x = GetSandboxStatsResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[32]
+ mi := &file_proto_worker_worker_proto_msgTypes[39]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1902,7 +2314,7 @@ func (x *GetSandboxStatsResponse) String() string {
func (*GetSandboxStatsResponse) ProtoMessage() {}
func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[32]
+ mi := &file_proto_worker_worker_proto_msgTypes[39]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1915,7 +2327,7 @@ func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetSandboxStatsResponse.ProtoReflect.Descriptor instead.
func (*GetSandboxStatsResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{32}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{39}
}
func (x *GetSandboxStatsResponse) GetCpuPercent() float64 {
@@ -1970,7 +2382,7 @@ type CreateCheckpointRequest struct {
func (x *CreateCheckpointRequest) Reset() {
*x = CreateCheckpointRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[33]
+ mi := &file_proto_worker_worker_proto_msgTypes[40]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1982,7 +2394,7 @@ func (x *CreateCheckpointRequest) String() string {
func (*CreateCheckpointRequest) ProtoMessage() {}
func (x *CreateCheckpointRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[33]
+ mi := &file_proto_worker_worker_proto_msgTypes[40]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1995,7 +2407,7 @@ func (x *CreateCheckpointRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use CreateCheckpointRequest.ProtoReflect.Descriptor instead.
func (*CreateCheckpointRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{33}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{40}
}
func (x *CreateCheckpointRequest) GetSandboxId() string {
@@ -2022,7 +2434,7 @@ type CreateCheckpointResponse struct {
func (x *CreateCheckpointResponse) Reset() {
*x = CreateCheckpointResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[34]
+ mi := &file_proto_worker_worker_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2034,7 +2446,7 @@ func (x *CreateCheckpointResponse) String() string {
func (*CreateCheckpointResponse) ProtoMessage() {}
func (x *CreateCheckpointResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[34]
+ mi := &file_proto_worker_worker_proto_msgTypes[41]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2047,7 +2459,7 @@ func (x *CreateCheckpointResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use CreateCheckpointResponse.ProtoReflect.Descriptor instead.
func (*CreateCheckpointResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{34}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{41}
}
func (x *CreateCheckpointResponse) GetRootfsS3Key() string {
@@ -2074,7 +2486,7 @@ type RestoreCheckpointRequest struct {
func (x *RestoreCheckpointRequest) Reset() {
*x = RestoreCheckpointRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[35]
+ mi := &file_proto_worker_worker_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2086,7 +2498,7 @@ func (x *RestoreCheckpointRequest) String() string {
func (*RestoreCheckpointRequest) ProtoMessage() {}
func (x *RestoreCheckpointRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[35]
+ mi := &file_proto_worker_worker_proto_msgTypes[42]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2099,7 +2511,7 @@ func (x *RestoreCheckpointRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RestoreCheckpointRequest.ProtoReflect.Descriptor instead.
func (*RestoreCheckpointRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{35}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{42}
}
func (x *RestoreCheckpointRequest) GetSandboxId() string {
@@ -2125,7 +2537,7 @@ type RestoreCheckpointResponse struct {
func (x *RestoreCheckpointResponse) Reset() {
*x = RestoreCheckpointResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[36]
+ mi := &file_proto_worker_worker_proto_msgTypes[43]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2137,7 +2549,7 @@ func (x *RestoreCheckpointResponse) String() string {
func (*RestoreCheckpointResponse) ProtoMessage() {}
func (x *RestoreCheckpointResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[36]
+ mi := &file_proto_worker_worker_proto_msgTypes[43]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2150,7 +2562,7 @@ func (x *RestoreCheckpointResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RestoreCheckpointResponse.ProtoReflect.Descriptor instead.
func (*RestoreCheckpointResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{36}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{43}
}
func (x *RestoreCheckpointResponse) GetSuccess() bool {
@@ -2308,7 +2720,44 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\recr_image_ref\x18\x04 \x01(\tR\vecrImageRef\"Q\n" +
"\x15BuildTemplateResponse\x12\x1b\n" +
"\timage_ref\x18\x01 \x01(\tR\bimageRef\x12\x1b\n" +
- "\tbuild_log\x18\x02 \x01(\tR\bbuildLog\"7\n" +
+ "\tbuild_log\x18\x02 \x01(\tR\bbuildLog\"\xd4\x02\n" +
+ "\x18ExecSessionCreateRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x18\n" +
+ "\acommand\x18\x02 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x03 \x03(\tR\x04args\x12>\n" +
+ "\x04envs\x18\x04 \x03(\v2*.worker.ExecSessionCreateRequest.EnvsEntryR\x04envs\x12\x10\n" +
+ "\x03cwd\x18\x05 \x01(\tR\x03cwd\x12'\n" +
+ "\x0ftimeout_seconds\x18\x06 \x01(\x05R\x0etimeoutSeconds\x127\n" +
+ "\x18max_run_after_disconnect\x18\a \x01(\x05R\x15maxRunAfterDisconnect\x1a7\n" +
+ "\tEnvsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\":\n" +
+ "\x19ExecSessionCreateResponse\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\"7\n" +
+ "\x16ExecSessionListRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"S\n" +
+ "\x17ExecSessionListResponse\x128\n" +
+ "\bsessions\x18\x01 \x03(\v2\x1c.worker.ExecSessionInfoEntryR\bsessions\"\xe4\x01\n" +
+ "\x14ExecSessionInfoEntry\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x18\n" +
+ "\acommand\x18\x02 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x03 \x03(\tR\x04args\x12\x18\n" +
+ "\arunning\x18\x04 \x01(\bR\arunning\x12\x1b\n" +
+ "\texit_code\x18\x05 \x01(\x05R\bexitCode\x12\x1d\n" +
+ "\n" +
+ "started_at\x18\x06 \x01(\x03R\tstartedAt\x12)\n" +
+ "\x10attached_clients\x18\a \x01(\x05R\x0fattachedClients\"n\n" +
+ "\x16ExecSessionKillRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x02 \x01(\tR\tsessionId\x12\x16\n" +
+ "\x06signal\x18\x03 \x01(\x05R\x06signal\"\x19\n" +
+ "\x17ExecSessionKillResponse\"7\n" +
"\x16GetSandboxStatsRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\xc4\x01\n" +
@@ -2333,8 +2782,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +
"\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\"5\n" +
"\x19RestoreCheckpointResponse\x12\x18\n" +
- "\asuccess\x18\x01 \x01(\bR\asuccess2\xcd\n" +
- "\n" +
+ "\asuccess\x18\x01 \x01(\bR\asuccess2\xcf\f\n" +
"\rSandboxWorker\x12L\n" +
"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +
"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +
@@ -2347,7 +2795,10 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\tWriteFile\x12\x18.worker.WriteFileRequest\x1a\x19.worker.WriteFileResponse\x12:\n" +
"\aListDir\x12\x16.worker.ListDirRequest\x1a\x17.worker.ListDirResponse\x12@\n" +
"\tCreatePTY\x12\x18.worker.CreatePTYRequest\x1a\x19.worker.CreatePTYResponse\x124\n" +
- "\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01\x12U\n" +
+ "\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01\x12X\n" +
+ "\x11ExecSessionCreate\x12 .worker.ExecSessionCreateRequest\x1a!.worker.ExecSessionCreateResponse\x12R\n" +
+ "\x0fExecSessionList\x12\x1e.worker.ExecSessionListRequest\x1a\x1f.worker.ExecSessionListResponse\x12R\n" +
+ "\x0fExecSessionKill\x12\x1e.worker.ExecSessionKillRequest\x1a\x1f.worker.ExecSessionKillResponse\x12U\n" +
"\x10HibernateSandbox\x12\x1f.worker.HibernateSandboxRequest\x1a .worker.HibernateSandboxResponse\x12F\n" +
"\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12O\n" +
"\x0eSaveAsTemplate\x12\x1d.worker.SaveAsTemplateRequest\x1a\x1e.worker.SaveAsTemplateResponse\x12U\n" +
@@ -2369,7 +2820,7 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {
}
var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 39)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 47)
var file_proto_worker_worker_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
@@ -2403,63 +2854,79 @@ var file_proto_worker_worker_proto_goTypes = []any{
(*SaveAsTemplateResponse)(nil), // 29: worker.SaveAsTemplateResponse
(*BuildTemplateRequest)(nil), // 30: worker.BuildTemplateRequest
(*BuildTemplateResponse)(nil), // 31: worker.BuildTemplateResponse
- (*GetSandboxStatsRequest)(nil), // 32: worker.GetSandboxStatsRequest
- (*GetSandboxStatsResponse)(nil), // 33: worker.GetSandboxStatsResponse
- (*CreateCheckpointRequest)(nil), // 34: worker.CreateCheckpointRequest
- (*CreateCheckpointResponse)(nil), // 35: worker.CreateCheckpointResponse
- (*RestoreCheckpointRequest)(nil), // 36: worker.RestoreCheckpointRequest
- (*RestoreCheckpointResponse)(nil), // 37: worker.RestoreCheckpointResponse
- nil, // 38: worker.CreateSandboxRequest.EnvsEntry
- nil, // 39: worker.ExecCommandRequest.EnvsEntry
+ (*ExecSessionCreateRequest)(nil), // 32: worker.ExecSessionCreateRequest
+ (*ExecSessionCreateResponse)(nil), // 33: worker.ExecSessionCreateResponse
+ (*ExecSessionListRequest)(nil), // 34: worker.ExecSessionListRequest
+ (*ExecSessionListResponse)(nil), // 35: worker.ExecSessionListResponse
+ (*ExecSessionInfoEntry)(nil), // 36: worker.ExecSessionInfoEntry
+ (*ExecSessionKillRequest)(nil), // 37: worker.ExecSessionKillRequest
+ (*ExecSessionKillResponse)(nil), // 38: worker.ExecSessionKillResponse
+ (*GetSandboxStatsRequest)(nil), // 39: worker.GetSandboxStatsRequest
+ (*GetSandboxStatsResponse)(nil), // 40: worker.GetSandboxStatsResponse
+ (*CreateCheckpointRequest)(nil), // 41: worker.CreateCheckpointRequest
+ (*CreateCheckpointResponse)(nil), // 42: worker.CreateCheckpointResponse
+ (*RestoreCheckpointRequest)(nil), // 43: worker.RestoreCheckpointRequest
+ (*RestoreCheckpointResponse)(nil), // 44: worker.RestoreCheckpointResponse
+ nil, // 45: worker.CreateSandboxRequest.EnvsEntry
+ nil, // 46: worker.ExecCommandRequest.EnvsEntry
+ nil, // 47: worker.ExecSessionCreateRequest.EnvsEntry
}
var file_proto_worker_worker_proto_depIdxs = []int32{
- 38, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 45, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
- 39, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 46, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream
17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry
22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize
- 1, // 6: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest
- 3, // 7: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest
- 5, // 8: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest
- 7, // 9: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest
- 9, // 10: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest
- 9, // 11: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest
- 12, // 12: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest
- 14, // 13: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest
- 16, // 14: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest
- 19, // 15: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest
- 21, // 16: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput
- 24, // 17: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest
- 26, // 18: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest
- 28, // 19: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest
- 34, // 20: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest
- 36, // 21: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest
- 30, // 22: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest
- 32, // 23: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest
- 2, // 24: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
- 4, // 25: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
- 6, // 26: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
- 8, // 27: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
- 10, // 28: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
- 11, // 29: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
- 13, // 30: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
- 15, // 31: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
- 18, // 32: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
- 20, // 33: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
- 23, // 34: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
- 25, // 35: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
- 27, // 36: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
- 29, // 37: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
- 35, // 38: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
- 37, // 39: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
- 31, // 40: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
- 33, // 41: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
- 24, // [24:42] is the sub-list for method output_type
- 6, // [6:24] is the sub-list for method input_type
- 6, // [6:6] is the sub-list for extension type_name
- 6, // [6:6] is the sub-list for extension extendee
- 0, // [0:6] is the sub-list for field type_name
+ 47, // 6: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
+ 36, // 7: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry
+ 1, // 8: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest
+ 3, // 9: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest
+ 5, // 10: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest
+ 7, // 11: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest
+ 9, // 12: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest
+ 9, // 13: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest
+ 12, // 14: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest
+ 14, // 15: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest
+ 16, // 16: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest
+ 19, // 17: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest
+ 21, // 18: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput
+ 32, // 19: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest
+ 34, // 20: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest
+ 37, // 21: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest
+ 24, // 22: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest
+ 26, // 23: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest
+ 28, // 24: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest
+ 41, // 25: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest
+ 43, // 26: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest
+ 30, // 27: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest
+ 39, // 28: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest
+ 2, // 29: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
+ 4, // 30: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
+ 6, // 31: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
+ 8, // 32: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
+ 10, // 33: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
+ 11, // 34: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
+ 13, // 35: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
+ 15, // 36: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
+ 18, // 37: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
+ 20, // 38: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
+ 23, // 39: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
+ 33, // 40: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
+ 35, // 41: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
+ 38, // 42: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
+ 25, // 43: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
+ 27, // 44: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
+ 29, // 45: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
+ 42, // 46: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
+ 44, // 47: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
+ 31, // 48: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
+ 40, // 49: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
+ 29, // [29:50] is the sub-list for method output_type
+ 8, // [8:29] is the sub-list for method input_type
+ 8, // [8:8] is the sub-list for extension type_name
+ 8, // [8:8] is the sub-list for extension extendee
+ 0, // [0:8] is the sub-list for field type_name
}
func init() { file_proto_worker_worker_proto_init() }
@@ -2477,7 +2944,7 @@ func file_proto_worker_worker_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 39,
+ NumMessages: 47,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 0679ee9b..91acad5f 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -20,6 +20,10 @@ service SandboxWorker {
rpc CreatePTY(CreatePTYRequest) returns (CreatePTYResponse);
rpc PTYStream(stream PTYInput) returns (stream PTYOutput);
+ rpc ExecSessionCreate(ExecSessionCreateRequest) returns (ExecSessionCreateResponse);
+ rpc ExecSessionList(ExecSessionListRequest) returns (ExecSessionListResponse);
+ rpc ExecSessionKill(ExecSessionKillRequest) returns (ExecSessionKillResponse);
+
rpc HibernateSandbox(HibernateSandboxRequest) returns (HibernateSandboxResponse);
rpc WakeSandbox(WakeSandboxRequest) returns (WakeSandboxResponse);
@@ -209,6 +213,50 @@ message BuildTemplateResponse {
string build_log = 2;
}
+// --- Exec Sessions ---
+
+message ExecSessionCreateRequest {
+ string sandbox_id = 1;
+ string command = 2;
+ repeated string args = 3;
+ map<string, string> envs = 4;
+ string cwd = 5;
+ int32 timeout_seconds = 6;
+ int32 max_run_after_disconnect = 7;
+}
+
+message ExecSessionCreateResponse {
+ string session_id = 1;
+}
+
+message ExecSessionListRequest {
+ string sandbox_id = 1;
+}
+
+message ExecSessionListResponse {
+ repeated ExecSessionInfoEntry sessions = 1;
+}
+
+message ExecSessionInfoEntry {
+ string session_id = 1;
+ string command = 2;
+ repeated string args = 3;
+ bool running = 4;
+ int32 exit_code = 5;
+ int64 started_at = 6;
+ int32 attached_clients = 7;
+}
+
+message ExecSessionKillRequest {
+ string sandbox_id = 1;
+ string session_id = 2;
+ int32 signal = 3;
+}
+
+message ExecSessionKillResponse {}
+
+// --- Stats ---
+
message GetSandboxStatsRequest {
string sandbox_id = 1;
}
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 8924a163..9696af6d 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
-// - protoc v6.33.4
+// - protoc v7.34.0
// source: proto/worker/worker.proto
package worker
@@ -30,6 +30,9 @@ const (
SandboxWorker_ListDir_FullMethodName = "/worker.SandboxWorker/ListDir"
SandboxWorker_CreatePTY_FullMethodName = "/worker.SandboxWorker/CreatePTY"
SandboxWorker_PTYStream_FullMethodName = "/worker.SandboxWorker/PTYStream"
+ SandboxWorker_ExecSessionCreate_FullMethodName = "/worker.SandboxWorker/ExecSessionCreate"
+ SandboxWorker_ExecSessionList_FullMethodName = "/worker.SandboxWorker/ExecSessionList"
+ SandboxWorker_ExecSessionKill_FullMethodName = "/worker.SandboxWorker/ExecSessionKill"
SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"
SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox"
SandboxWorker_SaveAsTemplate_FullMethodName = "/worker.SandboxWorker/SaveAsTemplate"
@@ -54,6 +57,9 @@ type SandboxWorkerClient interface {
ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error)
CreatePTY(ctx context.Context, in *CreatePTYRequest, opts ...grpc.CallOption) (*CreatePTYResponse, error)
PTYStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PTYInput, PTYOutput], error)
+ ExecSessionCreate(ctx context.Context, in *ExecSessionCreateRequest, opts ...grpc.CallOption) (*ExecSessionCreateResponse, error)
+ ExecSessionList(ctx context.Context, in *ExecSessionListRequest, opts ...grpc.CallOption) (*ExecSessionListResponse, error)
+ ExecSessionKill(ctx context.Context, in *ExecSessionKillRequest, opts ...grpc.CallOption) (*ExecSessionKillResponse, error)
HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error)
WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error)
SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error)
@@ -193,6 +199,36 @@ func (c *sandboxWorkerClient) PTYStream(ctx context.Context, opts ...grpc.CallOp
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type SandboxWorker_PTYStreamClient = grpc.BidiStreamingClient[PTYInput, PTYOutput]
+func (c *sandboxWorkerClient) ExecSessionCreate(ctx context.Context, in *ExecSessionCreateRequest, opts ...grpc.CallOption) (*ExecSessionCreateResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionCreateResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ExecSessionCreate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ExecSessionList(ctx context.Context, in *ExecSessionListRequest, opts ...grpc.CallOption) (*ExecSessionListResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionListResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ExecSessionList_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ExecSessionKill(ctx context.Context, in *ExecSessionKillRequest, opts ...grpc.CallOption) (*ExecSessionKillResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecSessionKillResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ExecSessionKill_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *sandboxWorkerClient) HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(HibernateSandboxResponse)
@@ -278,6 +314,9 @@ type SandboxWorkerServer interface {
ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error)
CreatePTY(context.Context, *CreatePTYRequest) (*CreatePTYResponse, error)
PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error
+ ExecSessionCreate(context.Context, *ExecSessionCreateRequest) (*ExecSessionCreateResponse, error)
+ ExecSessionList(context.Context, *ExecSessionListRequest) (*ExecSessionListResponse, error)
+ ExecSessionKill(context.Context, *ExecSessionKillRequest) (*ExecSessionKillResponse, error)
HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)
WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)
SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error)
@@ -328,6 +367,15 @@ func (UnimplementedSandboxWorkerServer) CreatePTY(context.Context, *CreatePTYReq
func (UnimplementedSandboxWorkerServer) PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error {
return status.Error(codes.Unimplemented, "method PTYStream not implemented")
}
+func (UnimplementedSandboxWorkerServer) ExecSessionCreate(context.Context, *ExecSessionCreateRequest) (*ExecSessionCreateResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionCreate not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ExecSessionList(context.Context, *ExecSessionListRequest) (*ExecSessionListResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionList not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ExecSessionKill(context.Context, *ExecSessionKillRequest) (*ExecSessionKillResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecSessionKill not implemented")
+}
func (UnimplementedSandboxWorkerServer) HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error) {
return nil, status.Error(codes.Unimplemented, "method HibernateSandbox not implemented")
}
@@ -550,6 +598,60 @@ func _SandboxWorker_PTYStream_Handler(srv interface{}, stream grpc.ServerStream)
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type SandboxWorker_PTYStreamServer = grpc.BidiStreamingServer[PTYInput, PTYOutput]
+func _SandboxWorker_ExecSessionCreate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionCreateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ExecSessionCreate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ExecSessionCreate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ExecSessionCreate(ctx, req.(*ExecSessionCreateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ExecSessionList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionListRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ExecSessionList(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ExecSessionList_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ExecSessionList(ctx, req.(*ExecSessionListRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ExecSessionKill_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecSessionKillRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ExecSessionKill(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ExecSessionKill_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ExecSessionKill(ctx, req.(*ExecSessionKillRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _SandboxWorker_HibernateSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HibernateSandboxRequest)
if err := dec(in); err != nil {
@@ -719,6 +821,18 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
MethodName: "CreatePTY",
Handler: _SandboxWorker_CreatePTY_Handler,
},
+ {
+ MethodName: "ExecSessionCreate",
+ Handler: _SandboxWorker_ExecSessionCreate_Handler,
+ },
+ {
+ MethodName: "ExecSessionList",
+ Handler: _SandboxWorker_ExecSessionList_Handler,
+ },
+ {
+ MethodName: "ExecSessionKill",
+ Handler: _SandboxWorker_ExecSessionKill_Handler,
+ },
{
MethodName: "HibernateSandbox",
Handler: _SandboxWorker_HibernateSandbox_Handler,
diff --git a/sdks/python/examples/test_exec.py b/sdks/python/examples/test_exec.py
new file mode 100644
index 00000000..3652f8b9
--- /dev/null
+++ b/sdks/python/examples/test_exec.py
@@ -0,0 +1,138 @@
+"""
+test_exec.py — End-to-end test for the session-based exec API (Python SDK)
+
+Usage:
+ cd sdks/python
+ pip install -e .
+ python examples/test_exec.py
+
+Environment:
+ OPENCOMPUTER_API_URL (default: http://50.17.44.74:8080)
+ OPENCOMPUTER_API_KEY (default: opensandbox-dev)
+"""
+
+import asyncio
+import os
+
+from opencomputer import Sandbox
+
+API_URL = os.environ.get("OPENCOMPUTER_API_URL", "http://50.17.44.74:8080")
+API_KEY = os.environ.get("OPENCOMPUTER_API_KEY", "opensandbox-dev")
+
+passed = 0
+failed = 0
+
+
+def check(condition: bool, msg: str):
+ global passed, failed
+ if condition:
+ passed += 1
+ print(f" ✓ {msg}")
+ else:
+ failed += 1
+ print(f" ✗ {msg}")
+
+
+async def main():
+ print("=== OpenSandbox Exec API Test (Python) ===\n")
+ print(f"API: {API_URL}")
+
+ # 1. Create sandbox
+ print("\n--- 1. Creating sandbox ---")
+ sandbox = await Sandbox.create(api_url=API_URL, api_key=API_KEY, template="base")
+ print(f" Sandbox: {sandbox.sandbox_id} ({sandbox.status})")
+ check(sandbox.status == "running", "sandbox is running")
+
+ try:
+ # 2. exec.run() — quick command
+ print("\n--- 2. exec.run('echo hello world') ---")
+ result = await sandbox.exec.run("echo hello world")
+ print(f' stdout: "{result.stdout.strip()}"')
+ check(result.exit_code == 0, f"exit code is 0 (got {result.exit_code})")
+ check(result.stdout.strip() == "hello world", "stdout matches")
+
+ # 3. exec.run() — ls
+ print("\n--- 3. exec.run('ls /') ---")
+ ls_result = await sandbox.exec.run("ls /")
+ check(ls_result.exit_code == 0, "exit code is 0")
+ check("usr" in ls_result.stdout, "stdout contains 'usr'")
+ check("bin" in ls_result.stdout, "stdout contains 'bin'")
+
+ # 4. exec.run() with env vars
+ print("\n--- 4. exec.run with env vars ---")
+ env_result = await sandbox.exec.run(
+ "echo $MY_VAR-$FOO", env={"MY_VAR": "hello", "FOO": "bar"}
+ )
+ print(f' output: "{env_result.stdout.strip()}"')
+ check(env_result.stdout.strip() == "hello-bar", "env vars passed correctly")
+
+ # 5. exec.run() with cwd
+ print("\n--- 5. exec.run('pwd') with cwd=/tmp ---")
+ cwd_result = await sandbox.exec.run("pwd", cwd="/tmp")
+ print(f' pwd: "{cwd_result.stdout.strip()}"')
+ check(cwd_result.stdout.strip() == "/tmp", "cwd is /tmp")
+
+ # 6. exec.run() — non-zero exit code
+ print("\n--- 6. exec.run('exit 42') ---")
+ fail_result = await sandbox.exec.run("exit 42")
+ print(f" exit: {fail_result.exit_code}")
+ check(fail_result.exit_code == 42, f"exit code is 42 (got {fail_result.exit_code})")
+
+ # 7. exec.run() — stderr
+ print("\n--- 7. exec.run stderr ---")
+ stderr_result = await sandbox.exec.run("echo error-msg >&2")
+ print(f' stderr: "{stderr_result.stderr.strip()}"')
+ check(stderr_result.stderr.strip() == "error-msg", "stderr captured")
+
+ # 8. exec.start() + list + kill
+ print("\n--- 8. exec.start('sleep 60') + list + kill ---")
+ session_id = await sandbox.exec.start("sleep", args=["60"])
+ print(f" session: {session_id}")
+
+ sessions = await sandbox.exec.list()
+ sleep_sessions = [s for s in sessions if s.session_id == session_id]
+ check(len(sleep_sessions) == 1, "session appears in list")
+ check(sleep_sessions[0].running, "session is running")
+
+ await sandbox.exec.kill(session_id)
+ print(" killed")
+ await asyncio.sleep(0.5)
+
+ sessions_after = await sandbox.exec.list()
+ killed = [s for s in sessions_after if s.session_id == session_id]
+ if killed:
+ check(not killed[0].running, "session is no longer running after kill")
+ else:
+ check(True, "session cleaned up after kill")
+
+ # 9. File write + read via exec
+ print("\n--- 9. Write file + cat ---")
+ await sandbox.files.write("/tmp/test.txt", "Hello from Python SDK!\n")
+ cat_result = await sandbox.exec.run("cat /tmp/test.txt")
+ print(f' cat: "{cat_result.stdout.strip()}"')
+ check(cat_result.stdout.strip() == "Hello from Python SDK!", "file content matches")
+
+ # 10. Multi-command script
+ print("\n--- 10. Multi-command script ---")
+ script_result = await sandbox.exec.run(
+ "echo hostname=$(hostname); echo user=$(whoami); echo arch=$(uname -m)"
+ )
+ print(f" {script_result.stdout.strip()}")
+ check("hostname=" in script_result.stdout, "has hostname")
+ check("user=" in script_result.stdout, "has user")
+
+ finally:
+ # 11. Cleanup
+ print("\n--- 11. Killing sandbox ---")
+ await sandbox.kill()
+ check(sandbox.status == "stopped", "sandbox stopped")
+ await sandbox.close()
+
+ # Summary
+ print(f"\n=== Results: {passed} passed, {failed} failed ===")
+ if failed > 0:
+ raise SystemExit(1)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index bb91090c..da9f2998 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -2,18 +2,19 @@
from opencomputer.sandbox import Sandbox
from opencomputer.filesystem import Filesystem
-from opencomputer.commands import Commands, ProcessResult
+from opencomputer.exec import Exec, ProcessResult, ExecSessionInfo
from opencomputer.pty import Pty, PtySession
from opencomputer.template import Template
__all__ = [
"Sandbox",
"Filesystem",
- "Commands",
+ "Exec",
"ProcessResult",
+ "ExecSessionInfo",
"Pty",
"PtySession",
"Template",
]
-__version__ = "0.4.4"
+__version__ = "0.5.0"
diff --git a/sdks/python/opencomputer/exec.py b/sdks/python/opencomputer/exec.py
new file mode 100644
index 00000000..5f3449d8
--- /dev/null
+++ b/sdks/python/opencomputer/exec.py
@@ -0,0 +1,174 @@
+"""Session-based exec API for running commands inside a sandbox."""
+
+from __future__ import annotations
+
+import struct
+from dataclasses import dataclass
+from typing import Any
+
+import httpx
+import websockets
+
+
+@dataclass
+class ProcessResult:
+ """Result of a command execution."""
+
+ exit_code: int
+ stdout: str
+ stderr: str
+
+
+@dataclass
+class ExecSessionInfo:
+ """Metadata for an exec session."""
+
+ session_id: str
+ sandbox_id: str
+ command: str
+ args: list[str]
+ running: bool
+ exit_code: int | None
+ started_at: str
+ attached_clients: int
+
+
+class Exec:
+ """Session-based command execution for a sandbox."""
+
+ def __init__(
+ self,
+ client: httpx.AsyncClient,
+ sandbox_id: str,
+ connect_url: str,
+ token: str,
+ ):
+ self._client = client
+ self._sandbox_id = sandbox_id
+ self._connect_url = connect_url
+ self._token = token
+
+ async def run(
+ self,
+ command: str,
+ timeout: int = 60,
+ env: dict[str, str] | None = None,
+ cwd: str | None = None,
+ ) -> ProcessResult:
+ """Run a shell command and wait for completion.
+
+ The command is executed via `sh -c`, so shell features like pipes,
+ redirects, and env var expansion work as expected.
+ """
+ body: dict[str, Any] = {"cmd": "sh", "args": ["-c", command]}
+ if env:
+ body["envs"] = env
+ if cwd:
+ body["cwd"] = cwd
+ if timeout:
+ body["timeout"] = timeout
+
+ resp = await self._client.post(
+ f"/sandboxes/{self._sandbox_id}/exec",
+ json=body,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ session_id = data["sessionID"]
+
+ # Attach via WebSocket and collect output
+ ws_url = self._connect_url.replace("http://", "ws://").replace(
+ "https://", "wss://"
+ )
+ ws_endpoint = f"{ws_url}/sandboxes/{self._sandbox_id}/exec/{session_id}"
+ if self._token:
+ ws_endpoint += f"?token={self._token}"
+
+ stdout_parts: list[bytes] = []
+ stderr_parts: list[bytes] = []
+ exit_code = -1
+
+ async with websockets.connect(ws_endpoint) as ws:
+ async for message in ws:
+ if isinstance(message, str):
+ continue
+ if len(message) < 1:
+ continue
+
+ stream_id = message[0]
+ payload = message[1:]
+
+ if stream_id == 0x01: # stdout
+ stdout_parts.append(payload)
+ elif stream_id == 0x02: # stderr
+ stderr_parts.append(payload)
+ elif stream_id == 0x03: # exit
+ if len(payload) >= 4:
+ exit_code = struct.unpack(">i", payload[:4])[0]
+ break
+ elif stream_id == 0x04: # scrollback_end
+ pass
+
+ return ProcessResult(
+ exit_code=exit_code,
+ stdout=b"".join(stdout_parts).decode("utf-8", errors="replace"),
+ stderr=b"".join(stderr_parts).decode("utf-8", errors="replace"),
+ )
+
+ async def start(
+ self,
+ command: str,
+ args: list[str] | None = None,
+ env: dict[str, str] | None = None,
+ cwd: str | None = None,
+ timeout: int | None = None,
+ ) -> str:
+ """Start a long-running command and return the session ID.
+
+ Unlike `run()`, this does not wait for completion. Use `list()` to
+ check session status, or `kill()` to stop it.
+ """
+ body: dict[str, Any] = {"cmd": command}
+ if args:
+ body["args"] = args
+ if env:
+ body["envs"] = env
+ if cwd:
+ body["cwd"] = cwd
+ if timeout is not None:
+ body["timeout"] = timeout
+
+ resp = await self._client.post(
+ f"/sandboxes/{self._sandbox_id}/exec",
+ json=body,
+ )
+ resp.raise_for_status()
+ return resp.json()["sessionID"]
+
+ async def list(self) -> list[ExecSessionInfo]:
+ """List all exec sessions for this sandbox."""
+ resp = await self._client.get(
+ f"/sandboxes/{self._sandbox_id}/exec",
+ )
+ resp.raise_for_status()
+ return [
+ ExecSessionInfo(
+ session_id=s["sessionID"],
+ sandbox_id=s.get("sandboxID", ""),
+ command=s["command"],
+ args=s.get("args") or [],
+ running=s["running"],
+ exit_code=s.get("exitCode"),
+ started_at=s.get("startedAt", ""),
+ attached_clients=s.get("attachedClients", 0),
+ )
+ for s in resp.json()
+ ]
+
+ async def kill(self, session_id: str, signal: int = 9) -> None:
+ """Kill an exec session."""
+ resp = await self._client.post(
+ f"/sandboxes/{self._sandbox_id}/exec/{session_id}/kill",
+ json={"signal": signal},
+ )
+ resp.raise_for_status()
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 31368b7c..9c499435 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -8,7 +8,7 @@ from typing import Any
import httpx
-from opencomputer.commands import Commands
+from opencomputer.exec import Exec
from opencomputer.filesystem import Filesystem
from opencomputer.pty import Pty
@@ -175,9 +175,9 @@ class Sandbox:
return Filesystem(self._ops_client, self.sandbox_id)
@property
- def commands(self) -> Commands:
- """Access command execution."""
- return Commands(self._ops_client, self.sandbox_id)
+ def exec(self) -> Exec:
+ """Access session-based command execution."""
+ return Exec(self._ops_client, self.sandbox_id, self._connect_url, self._token)
@property
def pty(self) -> Pty:
diff --git a/sdks/typescript/examples/test-exec.ts b/sdks/typescript/examples/test-exec.ts
new file mode 100644
index 00000000..8b026f1e
--- /dev/null
+++ b/sdks/typescript/examples/test-exec.ts
@@ -0,0 +1,178 @@
+/**
+ * test-exec.ts — End-to-end test for the session-based exec API
+ *
+ * Usage:
+ * cd sdks/typescript
+ * npx tsx test-exec.ts
+ *
+ * Environment:
+ * OPENCOMPUTER_API_URL (default: http://50.17.44.74:8080)
+ * OPENCOMPUTER_API_KEY (default: opensandbox-dev)
+ */
+
+import { Sandbox } from "../src/index.js";
+
+const API_URL = process.env.OPENCOMPUTER_API_URL || "http://50.17.44.74:8080";
+const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
+
+const decoder = new TextDecoder();
+let passed = 0;
+let failed = 0;
+
+function assert(condition: boolean, msg: string) {
+ if (condition) {
+ passed++;
+ console.log(` ✓ ${msg}`);
+ } else {
+ failed++;
+ console.log(` ✗ ${msg}`);
+ }
+}
+
+async function main() {
+ console.log("=== OpenSandbox Exec API Test ===\n");
+ console.log(`API: ${API_URL}`);
+
+ // 1. Create sandbox
+ console.log("\n--- 1. Creating sandbox ---");
+ const sandbox = await Sandbox.create({
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ template: "base",
+ });
+ console.log(` Sandbox: ${sandbox.sandboxId} (${sandbox.status})`);
+ assert(sandbox.status === "running", "sandbox is running");
+
+ // 2. exec.run() — quick command
+ console.log("\n--- 2. exec.run('echo hello world') ---");
+ const result = await sandbox.exec.run("echo hello world");
+ console.log(` stdout: "${result.stdout.trim()}"`);
+ assert(result.exitCode === 0, `exit code is 0 (got ${result.exitCode})`);
+ assert(result.stdout.trim() === "hello world", "stdout matches");
+
+ // 3. exec.run() — ls
+ console.log("\n--- 3. exec.run('ls /') ---");
+ const lsResult = await sandbox.exec.run("ls /");
+ assert(lsResult.exitCode === 0, "exit code is 0");
+ assert(lsResult.stdout.includes("usr"), "stdout contains 'usr'");
+ assert(lsResult.stdout.includes("bin"), "stdout contains 'bin'");
+
+ // 4. exec.run() with env vars
+ console.log("\n--- 4. exec.run with env vars ---");
+ const envResult = await sandbox.exec.run("echo $MY_VAR-$FOO", {
+ env: { MY_VAR: "hello", FOO: "bar" },
+ });
+ console.log(` output: "${envResult.stdout.trim()}"`);
+ assert(envResult.stdout.trim() === "hello-bar", "env vars passed correctly");
+
+ // 5. exec.run() with cwd
+ console.log("\n--- 5. exec.run('pwd') with cwd=/tmp ---");
+ const cwdResult = await sandbox.exec.run("pwd", { cwd: "/tmp" });
+ console.log(` pwd: "${cwdResult.stdout.trim()}"`);
+ assert(cwdResult.stdout.trim() === "/tmp", "cwd is /tmp");
+
+ // 6. exec.run() — non-zero exit code
+ console.log("\n--- 6. exec.run('exit 42') ---");
+ const failResult = await sandbox.exec.run("exit 42");
+ console.log(` exit: ${failResult.exitCode}`);
+ assert(
+ failResult.exitCode === 42,
+ `exit code is 42 (got ${failResult.exitCode})`,
+ );
+
+ // 7. exec.run() — stderr
+ console.log("\n--- 7. exec.run stderr ---");
+ const stderrResult = await sandbox.exec.run("echo error-msg >&2");
+ console.log(` stderr: "${stderrResult.stderr.trim()}"`);
+ assert(stderrResult.stderr.trim() === "error-msg", "stderr captured");
+
+ // 8. exec.start() — streaming output
+ console.log("\n--- 8. exec.start() — streaming ---");
+ const lines: string[] = [];
+ let streamExitCode = -1;
+ const session = await sandbox.exec.start("sh", {
+ args: ["-c", "for i in 1 2 3; do echo line-$i; sleep 0.1; done"],
+ onStdout: (data) => {
+ const text = decoder.decode(data);
+ text
+ .split("\n")
+ .filter(Boolean)
+ .forEach((l) => lines.push(l));
+ },
+ onExit: (code) => {
+ streamExitCode = code;
+ },
+ });
+ console.log(` session: ${session.sessionId}`);
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ assert(lines.includes("line-1"), "got line-1");
+ assert(lines.includes("line-3"), "got line-3");
+ assert(streamExitCode === 0, `stream exit code is 0 (got ${streamExitCode})`);
+
+ // 9. exec.list()
+ console.log("\n--- 9. exec.list() ---");
+ const sessions = await sandbox.exec.list();
+ console.log(` ${sessions.length} session(s)`);
+ assert(sessions.length > 0, "has sessions");
+
+ // 10. exec.start() + kill
+ console.log("\n--- 10. exec.start('sleep 60') + kill ---");
+ let killExitCode = -999;
+ const sleepSession = await sandbox.exec.start("sleep", {
+ args: ["60"],
+ onExit: (code) => {
+ killExitCode = code;
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ await sleepSession.kill();
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ console.log(` exit after kill: ${killExitCode}`);
+ assert(killExitCode !== -999, "got exit callback after kill");
+
+ // 11. File write + read via exec
+ console.log("\n--- 11. Write file + cat ---");
+ await sandbox.files.write("/tmp/test.txt", "Hello from SDK!\n");
+ const catResult = await sandbox.exec.run("cat /tmp/test.txt");
+ console.log(` cat: "${catResult.stdout.trim()}"`);
+ assert(catResult.stdout.trim() === "Hello from SDK!", "file content matches");
+
+ // 12. Multi-command shell script
+ console.log("\n--- 12. Multi-command script ---");
+ const scriptResult = await sandbox.exec.run(
+ "echo hostname=$(hostname); echo user=$(whoami); echo arch=$(uname -m)",
+ );
+ console.log(` ${scriptResult.stdout.trim()}`);
+ assert(scriptResult.stdout.includes("hostname="), "has hostname");
+ assert(scriptResult.stdout.includes("user="), "has user");
+
+ // 13. apt update shell script
+ console.log("\n--- 13. apt update script ---");
+ const aptUpdate = await sandbox.exec.start("apt", {
+ args: ["update"],
+ onStdout: (data) => {
+ const text = decoder.decode(data);
+ text
+ .split("\n")
+ .filter(Boolean)
+ .forEach((l) => lines.push(l));
+ },
+ onExit: (code) => {
+ killExitCode = code;
+ },
+ });
+
+ // 14. Cleanup
+ console.log("\n--- 13. Killing sandbox ---");
+ await sandbox.kill();
+ assert(sandbox.status === "stopped", "sandbox stopped");
+
+ // Summary
+ console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("\nTest failed:", err);
+ process.exit(1);
+});
diff --git a/sdks/typescript/src/commands.ts b/sdks/typescript/src/commands.ts
deleted file mode 100644
index c905fd45..00000000
--- a/sdks/typescript/src/commands.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-export interface ProcessResult {
- exitCode: number;
- stdout: string;
- stderr: string;
-}
-
-export interface RunOpts {
- timeout?: number;
- env?: Record<string, string>;
- cwd?: string;
-}
-
-export class Commands {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.token) {
- h["Authorization"] = `Bearer ${this.token}`;
- } else if (this.apiKey) {
- h["X-API-Key"] = this.apiKey;
- }
- return h;
- }
-
- async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {
- const timeout = opts.timeout ?? 60;
-
- const body: Record<string, unknown> = {
- cmd: command,
- timeout,
- };
- if (opts.env) body.envs = opts.env;
- if (opts.cwd) body.cwd = opts.cwd;
-
- const controller = new AbortController();
- const timeoutId = globalThis.setTimeout(() => controller.abort(), (timeout + 5) * 1000);
-
- try {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/commands`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- signal: controller.signal,
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Command failed: ${resp.status} ${text}`);
- }
-
- return await resp.json();
- } finally {
- globalThis.clearTimeout(timeoutId);
- }
- }
-}
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
new file mode 100644
index 00000000..a5860b26
--- /dev/null
+++ b/sdks/typescript/src/exec.ts
@@ -0,0 +1,207 @@
+export interface ProcessResult {
+ exitCode: number;
+ stdout: string;
+ stderr: string;
+}
+
+export interface RunOpts {
+ timeout?: number;
+ env?: Record<string, string>;
+ cwd?: string;
+}
+
+export interface ExecStartOpts {
+ args?: string[];
+ env?: Record<string, string>;
+ cwd?: string;
+ timeout?: number;
+ maxRunAfterDisconnect?: number;
+ onStdout?: (data: Uint8Array) => void;
+ onStderr?: (data: Uint8Array) => void;
+ onExit?: (exitCode: number) => void;
+}
+
+export interface ExecAttachOpts {
+ onStdout?: (data: Uint8Array) => void;
+ onStderr?: (data: Uint8Array) => void;
+ onExit?: (exitCode: number) => void;
+ onScrollbackEnd?: () => void;
+}
+
+export interface ExecSessionInfo {
+ sessionID: string;
+ sandboxID: string;
+ command: string;
+ args: string[];
+ running: boolean;
+ exitCode?: number;
+ startedAt: string;
+ attachedClients: number;
+}
+
+export interface ExecSession {
+ sessionId: string;
+ sendStdin(data: string | Uint8Array): void;
+ kill(signal?: number): Promise<void>;
+ close(): void;
+}
+
+export class Exec {
+ constructor(
+ private apiUrl: string,
+ private apiKey: string,
+ private sandboxId: string,
+ private token: string = "",
+ ) {}
+
+ private get headers(): Record<string, string> {
+ const h: Record<string, string> = { "Content-Type": "application/json" };
+ if (this.token) {
+ h["Authorization"] = `Bearer ${this.token}`;
+ } else if (this.apiKey) {
+ h["X-API-Key"] = this.apiKey;
+ }
+ return h;
+ }
+
+ async start(command: string, opts: ExecStartOpts = {}): Promise<ExecSession> {
+ const body: Record<string, unknown> = { cmd: command };
+ if (opts.args) body.args = opts.args;
+ if (opts.env) body.envs = opts.env;
+ if (opts.cwd) body.cwd = opts.cwd;
+ if (opts.timeout != null) body.timeout = opts.timeout;
+ if (opts.maxRunAfterDisconnect != null) body.maxRunAfterDisconnect = opts.maxRunAfterDisconnect;
+
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
+ method: "POST",
+ headers: this.headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to create exec session: ${resp.status} ${text}`);
+ }
+
+ const data = await resp.json();
+ const sessionId: string = data.sessionID;
+
+ return this.attach(sessionId, {
+ onStdout: opts.onStdout,
+ onStderr: opts.onStderr,
+ onExit: opts.onExit,
+ });
+ }
+
+ async attach(sessionId: string, opts: ExecAttachOpts = {}): Promise<ExecSession> {
+ const wsUrl = this.apiUrl
+ .replace("http://", "ws://")
+ .replace("https://", "wss://");
+ const tokenParam = this.token ? `?token=${encodeURIComponent(this.token)}` : "";
+ const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}${tokenParam}`;
+
+ const ws = new WebSocket(wsEndpoint);
+ ws.binaryType = "arraybuffer";
+
+ ws.onmessage = (event) => {
+ const buf = new Uint8Array(event.data as ArrayBuffer);
+ if (buf.length < 1) return;
+
+ const streamId = buf[0];
+ const payload = buf.slice(1);
+
+ switch (streamId) {
+ case 0x01: // stdout
+ opts.onStdout?.(payload);
+ break;
+ case 0x02: // stderr
+ opts.onStderr?.(payload);
+ break;
+ case 0x03: // exit
+ if (payload.length >= 4) {
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const exitCode = view.getInt32(0, false); // big-endian
+ opts.onExit?.(exitCode);
+ }
+ break;
+ case 0x04: // scrollback_end
+ opts.onScrollbackEnd?.();
+ break;
+ }
+ };
+
+ const exec = this;
+
+ return {
+ sessionId,
+ sendStdin(data: string | Uint8Array): void {
+ const payload = typeof data === "string"
+ ? new TextEncoder().encode(data)
+ : data;
+ const msg = new Uint8Array(1 + payload.length);
+ msg[0] = 0x00; // stdin stream ID
+ msg.set(payload, 1);
+ ws.send(msg);
+ },
+ async kill(signal?: number): Promise<void> {
+ await exec.kill(sessionId, signal);
+ },
+ close(): void {
+ ws.close();
+ },
+ };
+ }
+
+ async list(): Promise<ExecSessionInfo[]> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
+ headers: this.headers,
+ });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to list exec sessions: ${resp.status}`);
+ }
+
+ return resp.json();
+ }
+
+ async kill(sessionId: string, signal?: number): Promise<void> {
+ const body: Record<string, unknown> = {};
+ if (signal != null) body.signal = signal;
+
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}/kill`, {
+ method: "POST",
+ headers: this.headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to kill exec session: ${resp.status} ${text}`);
+ }
+ }
+
+ async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {
+ let stdout = "";
+ let stderr = "";
+
+ return new Promise<ProcessResult>((resolve, reject) => {
+ const decoder = new TextDecoder();
+
+ this.start("sh", {
+ args: ["-c", command],
+ env: opts.env,
+ cwd: opts.cwd,
+ timeout: opts.timeout,
+ onStdout: (data) => {
+ stdout += decoder.decode(data, { stream: true });
+ },
+ onStderr: (data) => {
+ stderr += decoder.decode(data, { stream: true });
+ },
+ onExit: (exitCode) => {
+ resolve({ exitCode, stdout, stderr });
+ },
+ }).catch(reject);
+ });
+ }
+}
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index 9b161035..34007b19 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -1,5 +1,5 @@
export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type PatchResult } from "./sandbox.js";
export { Filesystem, type EntryInfo } from "./filesystem.js";
-export { Commands, type ProcessResult, type RunOpts } from "./commands.js";
+export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
diff --git a/sdks/typescript/src/pty.ts b/sdks/typescript/src/pty.ts
index 8dddd212..30748c33 100644
--- a/sdks/typescript/src/pty.ts
+++ b/sdks/typescript/src/pty.ts
@@ -50,7 +50,8 @@ export class Pty {
const wsUrl = this.apiUrl
.replace("http://", "ws://")
.replace("https://", "wss://");
- const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/pty/${sessionId}`;
+ const tokenParam = this.token ? `?token=${encodeURIComponent(this.token)}` : "";
+ const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/pty/${sessionId}${tokenParam}`;
const ws = new WebSocket(wsEndpoint);
ws.binaryType = "arraybuffer";
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 9b81584c..1b2ba45d 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,5 +1,5 @@
import { Filesystem } from "./filesystem.js";
-import { Commands } from "./commands.js";
+import { Exec } from "./exec.js";
import { Pty } from "./pty.js";
function resolveApiUrl(url: string): string {
@@ -69,7 +69,7 @@ export interface PreviewURLResult {
export class Sandbox {
readonly sandboxId: string;
readonly files: Filesystem;
- readonly commands: Commands;
+ readonly exec: Exec;
readonly pty: Pty;
private apiUrl: string;
@@ -92,7 +92,7 @@ export class Sandbox {
const opsToken = this.connectUrl ? this.token : "";
this.files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- this.commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);
+ this.exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
this.pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
}
@@ -215,7 +215,7 @@ export class Sandbox {
const opsToken = this.connectUrl ? this.token : "";
(this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);
+ (this as any).exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
(this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
}
@@ -296,7 +296,7 @@ export class Sandbox {
const opsKey = this.connectUrl ? "" : this.apiKey;
const opsToken = this.connectUrl ? this.token : "";
(this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);
+ (this as any).exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
(this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
}