Skip to content

An open-source, faster Devin alternative

TypeScript

add claude agent sdk

motatoese4299d12dc15
diff --git a/cmd/agent/main.go b/cmd/agent/main.go
index 9e26582f..0fab6b80 100644
--- a/cmd/agent/main.go
+++ b/cmd/agent/main.go
@@ -9,6 +9,7 @@ import (
"log"
"os"
"os/signal"
+ "strings"
"syscall"
"github.com/opensandbox/opensandbox/internal/agent"
@@ -18,6 +19,14 @@ const version = "0.1.0"
func main() {
log.SetFlags(log.Ltime | log.Lmicroseconds)
+
+ // Ensure /usr/local/bin and /usr/local/sbin are in PATH for exec.LookPath.
+ // The init script may not set a full PATH.
+ path := os.Getenv("PATH")
+ if !strings.Contains(path, "/usr/local/bin") {
+ os.Setenv("PATH", "/usr/local/bin:/usr/local/sbin:"+path)
+ }
+
log.Printf("osb-agent %s starting", version)
// Listen on vsock port 1024 (inside Firecracker) or Unix socket (testing).
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index c2d62609..05466e74 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
+ "io"
"log"
"os"
"os/signal"
@@ -92,16 +93,21 @@ func main() {
scrollback := sandbox.NewScrollbackBuffer(0)
done := make(chan struct{})
+ // Create a pipe for stdin: writes to stdinW are forwarded to the gRPC stream
+ stdinR, stdinW := io.Pipe()
+
handle := &sandbox.ExecSessionHandle{
- ID: sessionID,
- SandboxID: sandboxID,
- Command: req.Command,
- Args: req.Args,
- Running: true,
- StartedAt: time.Now(),
- Done: done,
- Scrollback: scrollback,
+ ID: sessionID,
+ SandboxID: sandboxID,
+ Command: req.Command,
+ Args: req.Args,
+ Running: true,
+ StartedAt: time.Now(),
+ Done: done,
+ Scrollback: scrollback,
+ StdinWriter: stdinW,
OnKill: func(signal int) error {
+ stdinW.Close()
return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))
},
}
@@ -109,6 +115,7 @@ func main() {
// Attach to the session to pipe output into the host-side scrollback
go func() {
defer close(done)
+ defer stdinR.Close()
stream, err := agent.ExecSessionAttach(context.Background())
if err != nil {
return
@@ -117,6 +124,25 @@ func main() {
if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {
return
}
+
+ // Forward stdin pipe to gRPC stream in a separate goroutine
+ go func() {
+ buf := make([]byte, 4096)
+ for {
+ n, err := stdinR.Read(buf)
+ if err != nil {
+ return
+ }
+ if n > 0 {
+ data := make([]byte, n)
+ copy(data, buf[:n])
+ if err := stream.Send(&agentpb.ExecSessionInput{Stdin: data}); err != nil {
+ return
+ }
+ }
+ }
+ }()
+
for {
msg, err := stream.Recv()
if err != nil {
diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.sh
index 6f1d9189..9f06025e 100755
--- a/deploy/ec2/build-rootfs-docker.sh
+++ b/deploy/ec2/build-rootfs-docker.sh
@@ -149,6 +149,13 @@ exec /usr/local/bin/osb-agent
INIT_EOF
chmod +x "$TMPDIR/init"
+# Copy claude-agent-wrapper source (for images that include it)
+WRAPPER_DIR="$PROJECT_ROOT/scripts/claude-agent-wrapper"
+if [ -d "$WRAPPER_DIR" ]; then
+ mkdir -p "$TMPDIR/scripts"
+ cp -r "$WRAPPER_DIR" "$TMPDIR/scripts/claude-agent-wrapper"
+fi
+
# Append agent/init injection to Dockerfile
cat >> "$TMPDIR/Dockerfile" << 'INJECT_EOF'
diff --git a/deploy/firecracker/rootfs/Dockerfile.default b/deploy/firecracker/rootfs/Dockerfile.default
index ce70b401..b42a281a 100644
--- a/deploy/firecracker/rootfs/Dockerfile.default
+++ b/deploy/firecracker/rootfs/Dockerfile.default
@@ -76,6 +76,18 @@ RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& rm -rf /var/lib/apt/lists/* \
&& npm install -g npm@latest
+# ── Claude Agent SDK + wrapper ───────────────────────────────────────────────
+RUN npm install -g @anthropic-ai/claude-agent-sdk @anthropic-ai/claude-code
+COPY scripts/claude-agent-wrapper /tmp/claude-agent-wrapper
+RUN cd /tmp/claude-agent-wrapper \
+ && npm install --ignore-scripts \
+ && npx tsc \
+ && cp dist/index.js /usr/local/lib/claude-agent-wrapper.js \
+ && ln -sf /usr/lib/node_modules /usr/local/lib/node_modules \
+ && printf '#!/bin/sh\nexport IS_SANDBOX=1\nexec node --experimental-vm-modules /usr/local/lib/claude-agent-wrapper.js "$@"\n' > /usr/local/bin/claude-agent-wrapper \
+ && chmod +x /usr/local/bin/claude-agent-wrapper \
+ && rm -rf /tmp/claude-agent-wrapper
+
# ── Locale ───────────────────────────────────────────────────────────────────
RUN locale-gen en_US.UTF-8
ENV LANG=en_US.UTF-8
diff --git a/internal/agent/exec.go b/internal/agent/exec.go
index a87c41e8..82f51d4c 100644
--- a/internal/agent/exec.go
+++ b/internal/agent/exec.go
@@ -13,17 +13,32 @@ import (
pb "github.com/opensandbox/opensandbox/proto/agent"
)
-// baseEnv returns the current OS environment with HOME set to /root.
+// baseEnv returns the current OS environment with HOME set to /root and
+// PATH guaranteed to include /usr/local/bin and /usr/local/sbin.
// With overlayfs, the entire filesystem is backed by the data disk,
// so /root (the standard root home) has full disk space available.
func baseEnv() []string {
var env []string
+ hasPath := false
for _, e := range os.Environ() {
if strings.HasPrefix(e, "HOME=") {
continue
}
+ if strings.HasPrefix(e, "PATH=") {
+ hasPath = true
+ path := e[5:]
+ // Ensure /usr/local/bin and /usr/local/sbin are in PATH
+ if !strings.Contains(path, "/usr/local/bin") {
+ path = "/usr/local/bin:/usr/local/sbin:" + path
+ }
+ env = append(env, "PATH="+path)
+ continue
+ }
env = append(env, e)
}
+ if !hasPath {
+ env = append(env, "PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin")
+ }
env = append(env, "HOME=/root")
return env
}
diff --git a/internal/api/agent_session.go b/internal/api/agent_session.go
new file mode 100644
index 00000000..e5019905
--- /dev/null
+++ b/internal/api/agent_session.go
@@ -0,0 +1,214 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+func (s *Server) createAgentSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+
+ var req types.AgentSessionCreateRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body: " + err.Error(),
+ })
+ }
+
+ execReq := types.ExecSessionCreateRequest{
+ Command: "claude-agent-wrapper",
+ }
+
+ var session *sandbox.ExecSessionHandle
+
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.execSessionManager.CreateSession(id, execReq)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "agentSessionCreate", 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()})
+ }
+ }
+
+ // Send configure command if any config options provided
+ hasConfig := req.Model != "" || req.SystemPrompt != "" || len(req.AllowedTools) > 0 ||
+ req.PermissionMode != "" || req.MaxTurns > 0 || req.Cwd != "" || len(req.McpServers) > 0
+ if hasConfig && session.StdinWriter != nil {
+ configCmd := map[string]interface{}{"type": "configure"}
+ if req.Model != "" {
+ configCmd["model"] = req.Model
+ }
+ if req.SystemPrompt != "" {
+ configCmd["systemPrompt"] = req.SystemPrompt
+ }
+ if len(req.AllowedTools) > 0 {
+ configCmd["allowedTools"] = req.AllowedTools
+ }
+ if req.PermissionMode != "" {
+ configCmd["permissionMode"] = req.PermissionMode
+ }
+ if req.MaxTurns > 0 {
+ configCmd["maxTurns"] = req.MaxTurns
+ }
+ if req.Cwd != "" {
+ configCmd["cwd"] = req.Cwd
+ }
+ if len(req.McpServers) > 0 {
+ configCmd["mcpServers"] = req.McpServers
+ }
+ configJSON, _ := json.Marshal(configCmd)
+ session.StdinWriter.Write(append(configJSON, '\n'))
+ }
+
+ // Send initial prompt if provided
+ if req.Prompt != "" && session.StdinWriter != nil {
+ promptCmd := map[string]interface{}{
+ "type": "prompt",
+ "text": req.Prompt,
+ }
+ promptJSON, _ := json.Marshal(promptCmd)
+ session.StdinWriter.Write(append(promptJSON, '\n'))
+ }
+
+ return c.JSON(http.StatusCreated, types.AgentSessionInfo{
+ SessionID: session.ID,
+ SandboxID: id,
+ Running: true,
+ StartedAt: session.StartedAt.Format(time.RFC3339),
+ })
+}
+
+func (s *Server) listAgentSessions(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+ allSessions := s.execSessionManager.ListSessions(id)
+
+ var agentSessions []types.AgentSessionInfo
+ for _, sess := range allSessions {
+ if sess.Command == "claude-agent-wrapper" {
+ agentSessions = append(agentSessions, types.AgentSessionInfo{
+ SessionID: sess.SessionID,
+ SandboxID: sess.SandboxID,
+ Running: sess.Running,
+ StartedAt: sess.StartedAt,
+ })
+ }
+ }
+
+ if agentSessions == nil {
+ agentSessions = []types.AgentSessionInfo{}
+ }
+
+ return c.JSON(http.StatusOK, agentSessions)
+}
+
+func (s *Server) sendAgentPrompt(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ sessionID := c.Param("sid")
+
+ var req types.AgentPromptRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if req.Text == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "text is required"})
+ }
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ if session.StdinWriter == nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session stdin not available"})
+ }
+
+ promptCmd := map[string]interface{}{
+ "type": "prompt",
+ "text": req.Text,
+ }
+ promptJSON, _ := json.Marshal(promptCmd)
+ session.StdinWriter.Write(append(promptJSON, '\n'))
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) interruptAgent(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ sessionID := c.Param("sid")
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ if session.StdinWriter == nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session stdin not available"})
+ }
+
+ interruptCmd := map[string]interface{}{"type": "interrupt"}
+ interruptJSON, _ := json.Marshal(interruptCmd)
+ session.StdinWriter.Write(append(interruptJSON, '\n'))
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) killAgentSession(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ id := c.Param("id")
+ sessionID := c.Param("sid")
+
+ var body struct {
+ Signal int `json:"signal"`
+ }
+ _ = c.Bind(&body)
+
+ 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, "agentSessionKill", 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 4e3518c0..852d99e8 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -161,6 +161,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
+ // Agent sessions (Claude Agent SDK)
+ api.POST("/sandboxes/:id/agent", s.createAgentSession)
+ api.GET("/sandboxes/:id/agent", s.listAgentSessions)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
+ api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
+
// Filesystem
api.GET("/sandboxes/:id/files", s.readFile)
api.PUT("/sandboxes/:id/files", s.writeFile)
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index b2fac43c..523f4596 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -3,6 +3,7 @@ package worker
import (
"context"
"encoding/binary"
+ "encoding/json"
"io"
"net/http"
"time"
@@ -15,6 +16,9 @@ import (
"github.com/opensandbox/opensandbox/pkg/types"
)
+// jsonMarshal is a helper to marshal JSON for agent session stdin commands.
+var jsonMarshal = json.Marshal
+
func (s *HTTPServer) setTimeout(c echo.Context) error {
if s.router == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
@@ -549,6 +553,211 @@ func (s *HTTPServer) resizePTY(c echo.Context) error {
return c.NoContent(http.StatusOK)
}
+// --- Agent session handlers ---
+// These are thin wrappers over exec sessions that run the claude-agent-wrapper process.
+
+func (s *HTTPServer) createAgentSession(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 req types.AgentSessionCreateRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+
+ // Create exec session running the claude-agent-wrapper
+ execReq := types.ExecSessionCreateRequest{
+ Command: "claude-agent-wrapper",
+ }
+
+ var session *sandbox.ExecSessionHandle
+
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.execSessionManager.CreateSession(id, execReq)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "agentSessionCreate", 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()})
+ }
+ }
+
+ // Send configure command if any config options provided
+ hasConfig := req.Model != "" || req.SystemPrompt != "" || len(req.AllowedTools) > 0 ||
+ req.PermissionMode != "" || req.MaxTurns > 0 || req.Cwd != "" || len(req.McpServers) > 0
+ if hasConfig && session.StdinWriter != nil {
+ configCmd := map[string]interface{}{"type": "configure"}
+ if req.Model != "" {
+ configCmd["model"] = req.Model
+ }
+ if req.SystemPrompt != "" {
+ configCmd["systemPrompt"] = req.SystemPrompt
+ }
+ if len(req.AllowedTools) > 0 {
+ configCmd["allowedTools"] = req.AllowedTools
+ }
+ if req.PermissionMode != "" {
+ configCmd["permissionMode"] = req.PermissionMode
+ }
+ if req.MaxTurns > 0 {
+ configCmd["maxTurns"] = req.MaxTurns
+ }
+ if req.Cwd != "" {
+ configCmd["cwd"] = req.Cwd
+ }
+ if len(req.McpServers) > 0 {
+ configCmd["mcpServers"] = req.McpServers
+ }
+ configJSON, _ := jsonMarshal(configCmd)
+ session.StdinWriter.Write(append(configJSON, '\n'))
+ }
+
+ // Send initial prompt if provided
+ if req.Prompt != "" && session.StdinWriter != nil {
+ promptCmd := map[string]interface{}{
+ "type": "prompt",
+ "text": req.Prompt,
+ }
+ promptJSON, _ := jsonMarshal(promptCmd)
+ session.StdinWriter.Write(append(promptJSON, '\n'))
+ }
+
+ return c.JSON(http.StatusCreated, types.AgentSessionInfo{
+ SessionID: session.ID,
+ SandboxID: id,
+ Running: true,
+ StartedAt: session.StartedAt.Format(time.RFC3339),
+ })
+}
+
+func (s *HTTPServer) listAgentSessions(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")
+ allSessions := s.execSessionManager.ListSessions(id)
+
+ // Filter to only agent sessions (command = claude-agent-wrapper)
+ var agentSessions []types.AgentSessionInfo
+ for _, sess := range allSessions {
+ if sess.Command == "claude-agent-wrapper" {
+ agentSessions = append(agentSessions, types.AgentSessionInfo{
+ SessionID: sess.SessionID,
+ SandboxID: sess.SandboxID,
+ Running: sess.Running,
+ StartedAt: sess.StartedAt,
+ })
+ }
+ }
+
+ if agentSessions == nil {
+ agentSessions = []types.AgentSessionInfo{}
+ }
+
+ return c.JSON(http.StatusOK, agentSessions)
+}
+
+func (s *HTTPServer) sendAgentPrompt(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
+ sessionID := c.Param("sid")
+
+ var req types.AgentPromptRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if req.Text == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "text is required"})
+ }
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ if session.StdinWriter == nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session stdin not available"})
+ }
+
+ promptCmd := map[string]interface{}{
+ "type": "prompt",
+ "text": req.Text,
+ }
+ promptJSON, _ := jsonMarshal(promptCmd)
+ session.StdinWriter.Write(append(promptJSON, '\n'))
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) interruptAgent(c echo.Context) error {
+ if s.execSessionManager == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "exec sessions not available"})
+ }
+
+ sessionID := c.Param("sid")
+
+ session, err := s.execSessionManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ if session.StdinWriter == nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session stdin not available"})
+ }
+
+ interruptCmd := map[string]interface{}{"type": "interrupt"}
+ interruptJSON, _ := jsonMarshal(interruptCmd)
+ session.StdinWriter.Write(append(interruptJSON, '\n'))
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) killAgentSession(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("sid")
+
+ var body struct {
+ Signal int `json:"signal"`
+ }
+ _ = c.Bind(&body)
+
+ 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, "agentSessionKill", 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)
+}
+
// refreshToken issues a fresh 24h JWT for a sandbox.
// The caller must already be authenticated (existing valid JWT via middleware).
func (s *HTTPServer) refreshToken(c echo.Context) error {
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index 19ea1b9a..40b4614d 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -100,6 +100,13 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
// Token refresh
api.POST("/sandboxes/:id/token/refresh", s.refreshToken)
+ // Agent sessions (Claude Agent SDK)
+ api.POST("/sandboxes/:id/agent", s.createAgentSession)
+ api.GET("/sandboxes/:id/agent", s.listAgentSessions)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
+ api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
+
// PTY
api.POST("/sandboxes/:id/pty", s.createPTY)
api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
diff --git a/pkg/types/agent_session.go b/pkg/types/agent_session.go
new file mode 100644
index 00000000..033ce575
--- /dev/null
+++ b/pkg/types/agent_session.go
@@ -0,0 +1,26 @@
+package types
+
+// AgentSessionCreateRequest is the request body for creating an agent session.
+type AgentSessionCreateRequest struct {
+ Prompt string `json:"prompt,omitempty"`
+ Model string `json:"model,omitempty"`
+ SystemPrompt string `json:"systemPrompt,omitempty"`
+ AllowedTools []string `json:"allowedTools,omitempty"`
+ PermissionMode string `json:"permissionMode,omitempty"`
+ MaxTurns int `json:"maxTurns,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ McpServers map[string]interface{} `json:"mcpServers,omitempty"`
+}
+
+// AgentSessionInfo is the response body for agent session metadata.
+type AgentSessionInfo struct {
+ SessionID string `json:"sessionID"`
+ SandboxID string `json:"sandboxID"`
+ Running bool `json:"running"`
+ StartedAt string `json:"startedAt"`
+}
+
+// AgentPromptRequest is the request body for sending a prompt to an agent session.
+type AgentPromptRequest struct {
+ Text string `json:"text"`
+}
diff --git a/scripts/build-rootfs.sh b/scripts/build-rootfs.sh
index bf90c11c..db594464 100755
--- a/scripts/build-rootfs.sh
+++ b/scripts/build-rootfs.sh
@@ -198,6 +198,11 @@ build_image() {
generate_init_script > "$tmpdir/init"
chmod +x "$tmpdir/init"
+ # Copy claude-agent-wrapper source (for images that include it)
+ if [ -d "$SCRIPT_DIR/claude-agent-wrapper" ]; then
+ cp -r "$SCRIPT_DIR/claude-agent-wrapper" "$tmpdir/scripts/claude-agent-wrapper"
+ fi
+
# Append agent/init injection to Dockerfile
cat >> "$tmpdir/Dockerfile" << 'INJECT_EOF'
diff --git a/scripts/claude-agent-wrapper/index.ts b/scripts/claude-agent-wrapper/index.ts
new file mode 100644
index 00000000..32a2697e
--- /dev/null
+++ b/scripts/claude-agent-wrapper/index.ts
@@ -0,0 +1,206 @@
+#!/usr/bin/env node
+
+/**
+ * claude-agent-wrapper
+ *
+ * In-VM wrapper that bridges the Claude Agent SDK with a JSON-line stdio protocol.
+ * Runs as an exec session process: reads JSON commands from stdin, emits structured
+ * events as JSON lines on stdout.
+ *
+ * Stdin protocol (JSON lines):
+ * {"type":"configure","model":"...","allowedTools":[...],...}
+ * {"type":"prompt","text":"Fix the bug in auth.py"}
+ * {"type":"interrupt"}
+ *
+ * Stdout protocol (JSON lines):
+ * {"type":"ready"}
+ * {"type":"assistant","message":{...},"session_id":"..."}
+ * {"type":"result","subtype":"success","result":"...","total_cost_usd":0.01,...}
+ * {"type":"turn_complete"}
+ * {"type":"interrupted"}
+ * {"type":"error","message":"..."}
+ */
+
+import { createInterface } from "node:readline";
+import { query } from "@anthropic-ai/claude-agent-sdk";
+import type { Options, SDKMessage, Query } from "@anthropic-ai/claude-agent-sdk";
+
+// --- Types ---
+
+interface ConfigureCommand {
+ type: "configure";
+ model?: string;
+ allowedTools?: string[];
+ disallowedTools?: string[];
+ systemPrompt?: string;
+ permissionMode?: string;
+ maxTurns?: number;
+ cwd?: string;
+ mcpServers?: Record<string, unknown>;
+}
+
+interface PromptCommand {
+ type: "prompt";
+ text: string;
+}
+
+interface InterruptCommand {
+ type: "interrupt";
+}
+
+type Command = ConfigureCommand | PromptCommand | InterruptCommand;
+
+// --- State ---
+
+let config: ConfigureCommand = {
+ type: "configure",
+ model: "claude-sonnet-4-20250514",
+ permissionMode: "bypassPermissions",
+ cwd: process.env.HOME || "/home/user",
+};
+
+let activeQuery: Query | null = null;
+
+// --- Helpers ---
+
+function emit(event: Record<string, unknown>): void {
+ process.stdout.write(JSON.stringify(event) + "\n");
+}
+
+function logError(msg: string): void {
+ process.stderr.write(`[claude-agent-wrapper] ${msg}\n`);
+}
+
+// --- Command handlers ---
+
+function handleConfigure(cmd: ConfigureCommand): void {
+ config = { ...config, ...cmd };
+ emit({ type: "configured" });
+}
+
+async function handlePrompt(cmd: PromptCommand): Promise<void> {
+ const options: Options = {
+ maxTurns: config.maxTurns ?? 50,
+ permissionMode: (config.permissionMode as Options["permissionMode"]) ?? "bypassPermissions",
+ allowDangerouslySkipPermissions: config.permissionMode === "bypassPermissions",
+ };
+
+ if (config.model) {
+ options.model = config.model;
+ }
+
+ if (config.systemPrompt) {
+ options.systemPrompt = config.systemPrompt;
+ }
+
+ if (config.cwd) {
+ options.cwd = config.cwd;
+ }
+
+ if (config.allowedTools && config.allowedTools.length > 0) {
+ options.allowedTools = config.allowedTools;
+ }
+
+ if (config.disallowedTools && config.disallowedTools.length > 0) {
+ options.disallowedTools = config.disallowedTools;
+ }
+
+ if (config.mcpServers) {
+ options.mcpServers = config.mcpServers as Options["mcpServers"];
+ }
+
+ try {
+ activeQuery = query({ prompt: cmd.text, options });
+
+ for await (const message of activeQuery) {
+ emitMessage(message);
+ }
+
+ emit({ type: "turn_complete" });
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (message.includes("abort") || message.includes("interrupt")) {
+ emit({ type: "interrupted" });
+ } else {
+ logError(`prompt error: ${message}`);
+ emit({ type: "error", message });
+ }
+ } finally {
+ activeQuery = null;
+ }
+}
+
+function emitMessage(msg: SDKMessage): void {
+ // Forward the message as-is — the SDK client will parse by `type` field
+ // Strip any non-serializable properties
+ const serializable: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(msg)) {
+ if (typeof value !== "function") {
+ serializable[key] = value;
+ }
+ }
+ emit(serializable);
+}
+
+async function handleInterrupt(): Promise<void> {
+ if (activeQuery) {
+ try {
+ await activeQuery.interrupt();
+ } catch {
+ // Query may already be done
+ }
+ } else {
+ emit({ type: "interrupted" });
+ }
+}
+
+// --- Main loop ---
+
+async function main(): Promise<void> {
+ // Verify API key is available
+ if (!process.env.ANTHROPIC_API_KEY) {
+ emit({ type: "error", message: "ANTHROPIC_API_KEY environment variable is not set" });
+ process.exit(1);
+ }
+
+ emit({ type: "ready" });
+
+ const rl = createInterface({ input: process.stdin });
+
+ for await (const line of rl) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ let cmd: Command;
+ try {
+ cmd = JSON.parse(trimmed) as Command;
+ } catch {
+ logError(`invalid JSON: ${trimmed}`);
+ emit({ type: "error", message: "invalid JSON input" });
+ continue;
+ }
+
+ switch (cmd.type) {
+ case "configure":
+ handleConfigure(cmd);
+ break;
+ case "prompt":
+ if (!cmd.text) {
+ emit({ type: "error", message: "prompt text is required" });
+ break;
+ }
+ await handlePrompt(cmd);
+ break;
+ case "interrupt":
+ await handleInterrupt();
+ break;
+ default:
+ emit({ type: "error", message: `unknown command type: ${(cmd as { type: string }).type}` });
+ }
+ }
+}
+
+main().catch((err) => {
+ logError(`fatal: ${err}`);
+ process.exit(1);
+});
diff --git a/scripts/claude-agent-wrapper/package-lock.json b/scripts/claude-agent-wrapper/package-lock.json
new file mode 100644
index 00000000..9236e403
--- /dev/null
+++ b/scripts/claude-agent-wrapper/package-lock.json
@@ -0,0 +1,387 @@
+{
+ "name": "claude-agent-wrapper",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "claude-agent-wrapper",
+ "version": "1.0.0",
+ "dependencies": {
+ "@anthropic-ai/claude-agent-sdk": "^0.2.71"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.5.0"
+ }
+ },
+ "node_modules/@anthropic-ai/claude-agent-sdk": {
+ "version": "0.2.71",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.2.71.tgz",
+ "integrity": "sha512-pIsQJnM7Y+cJHL7aFY6SCCW3FIni218gVEpPqG8XGowfYxboFNBbNssWiUNRwthT8bp9jypcX7q5kx0Xsw14xg==",
+ "license": "SEE LICENSE IN README.md",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "^0.34.2",
+ "@img/sharp-darwin-x64": "^0.34.2",
+ "@img/sharp-linux-arm": "^0.34.2",
+ "@img/sharp-linux-arm64": "^0.34.2",
+ "@img/sharp-linux-x64": "^0.34.2",
+ "@img/sharp-linuxmusl-arm64": "^0.34.2",
+ "@img/sharp-linuxmusl-x64": "^0.34.2",
+ "@img/sharp-win32-arm64": "^0.34.2",
+ "@img/sharp-win32-x64": "^0.34.2"
+ },
+ "peerDependencies": {
+ "zod": "^4.0.0"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.37",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz",
+ "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/zod": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/scripts/claude-agent-wrapper/package.json b/scripts/claude-agent-wrapper/package.json
new file mode 100644
index 00000000..7fc21cdf
--- /dev/null
+++ b/scripts/claude-agent-wrapper/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "claude-agent-wrapper",
+ "version": "1.0.0",
+ "description": "In-VM wrapper for Claude Agent SDK, bridging JSON-line stdio protocol",
+ "type": "module",
+ "main": "dist/index.js",
+ "scripts": {
+ "build": "tsc"
+ },
+ "dependencies": {
+ "@anthropic-ai/claude-agent-sdk": "^0.2.71"
+ },
+ "devDependencies": {
+ "typescript": "^5.5.0",
+ "@types/node": "^20.0.0"
+ }
+}
diff --git a/scripts/claude-agent-wrapper/tsconfig.json b/scripts/claude-agent-wrapper/tsconfig.json
new file mode 100644
index 00000000..50cc7984
--- /dev/null
+++ b/scripts/claude-agent-wrapper/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "declaration": true
+ },
+ "include": ["index.ts"]
+}
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index da9f2998..e52d1f77 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -1,6 +1,7 @@
"""OpenComputer Python SDK - cloud sandbox platform."""
from opencomputer.sandbox import Sandbox
+from opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfo
from opencomputer.filesystem import Filesystem
from opencomputer.exec import Exec, ProcessResult, ExecSessionInfo
from opencomputer.pty import Pty, PtySession
@@ -8,6 +9,10 @@ from opencomputer.template import Template
__all__ = [
"Sandbox",
+ "Agent",
+ "AgentEvent",
+ "AgentSession",
+ "AgentSessionInfo",
"Filesystem",
"Exec",
"ProcessResult",
diff --git a/sdks/python/opencomputer/agent.py b/sdks/python/opencomputer/agent.py
new file mode 100644
index 00000000..2d3ac681
--- /dev/null
+++ b/sdks/python/opencomputer/agent.py
@@ -0,0 +1,333 @@
+"""Agent session API for running Claude Agent SDK inside a sandbox."""
+
+from __future__ import annotations
+
+import json
+import struct
+from dataclasses import dataclass
+from typing import Any, Callable
+
+import httpx
+import websockets
+
+
+@dataclass
+class AgentEvent:
+ """A structured event from the Claude agent."""
+
+ type: str
+ data: dict[str, Any]
+
+ def __getitem__(self, key: str) -> Any:
+ if key == "type":
+ return self.type
+ return self.data[key]
+
+ def get(self, key: str, default: Any = None) -> Any:
+ if key == "type":
+ return self.type
+ return self.data.get(key, default)
+
+
+@dataclass
+class AgentSessionInfo:
+ """Metadata for an agent session."""
+
+ session_id: str
+ sandbox_id: str
+ running: bool
+ started_at: str
+
+
+class Agent:
+ """Claude Agent SDK integration 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 start(
+ self,
+ prompt: str | None = None,
+ model: str | None = None,
+ system_prompt: str | None = None,
+ allowed_tools: list[str] | None = None,
+ permission_mode: str | None = None,
+ max_turns: int | None = None,
+ cwd: str | None = None,
+ mcp_servers: dict[str, Any] | None = None,
+ on_event: Callable[[AgentEvent], None] | None = None,
+ on_error: Callable[[str], None] | None = None,
+ ) -> AgentSession:
+ """Start a new agent session.
+
+ Args:
+ prompt: Initial prompt to send to the agent.
+ model: Claude model to use (default: claude-sonnet-4-20250514).
+ system_prompt: Custom system instructions.
+ allowed_tools: Built-in tools to enable.
+ permission_mode: Permission mode for tool execution.
+ max_turns: Max agentic turns per prompt.
+ cwd: Working directory inside the sandbox.
+ mcp_servers: MCP server configurations.
+ on_event: Callback for structured agent events.
+ on_error: Callback for stderr/error output.
+
+ Returns:
+ An AgentSession that can be used to interact with the agent.
+ """
+ body: dict[str, Any] = {}
+ if prompt:
+ body["prompt"] = prompt
+ if model:
+ body["model"] = model
+ if system_prompt:
+ body["systemPrompt"] = system_prompt
+ if allowed_tools:
+ body["allowedTools"] = allowed_tools
+ if permission_mode:
+ body["permissionMode"] = permission_mode
+ if max_turns is not None:
+ body["maxTurns"] = max_turns
+ if cwd:
+ body["cwd"] = cwd
+ if mcp_servers:
+ body["mcpServers"] = mcp_servers
+
+ resp = await self._client.post(
+ f"/sandboxes/{self._sandbox_id}/agent",
+ json=body,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ session_id = data["sessionID"]
+
+ return await self.attach(
+ session_id,
+ on_event=on_event,
+ on_error=on_error,
+ )
+
+ async def attach(
+ self,
+ session_id: str,
+ on_event: Callable[[AgentEvent], None] | None = None,
+ on_error: Callable[[str], None] | None = None,
+ ) -> AgentSession:
+ """Attach to an existing agent session.
+
+ Reconnects via WebSocket and replays scrollback events.
+
+ Args:
+ session_id: The session ID to attach to.
+ on_event: Callback for structured agent events.
+ on_error: Callback for stderr/error output.
+
+ Returns:
+ An AgentSession for interaction.
+ """
+ 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}"
+
+ ws = await websockets.connect(ws_endpoint)
+
+ return AgentSession(
+ session_id=session_id,
+ sandbox_id=self._sandbox_id,
+ ws=ws,
+ client=self._client,
+ on_event=on_event,
+ on_error=on_error,
+ )
+
+ async def list(self) -> list[AgentSessionInfo]:
+ """List all agent sessions for this sandbox."""
+ resp = await self._client.get(
+ f"/sandboxes/{self._sandbox_id}/agent",
+ )
+ resp.raise_for_status()
+ return [
+ AgentSessionInfo(
+ session_id=s["sessionID"],
+ sandbox_id=s.get("sandboxID", ""),
+ running=s["running"],
+ started_at=s.get("startedAt", ""),
+ )
+ for s in resp.json()
+ ]
+
+
+class AgentSession:
+ """A connected agent session with WebSocket streaming."""
+
+ def __init__(
+ self,
+ session_id: str,
+ sandbox_id: str,
+ ws: websockets.WebSocketClientProtocol,
+ client: httpx.AsyncClient,
+ on_event: Callable[[AgentEvent], None] | None = None,
+ on_error: Callable[[str], None] | None = None,
+ ):
+ self.session_id = session_id
+ self.sandbox_id = sandbox_id
+ self._ws = ws
+ self._client = client
+ self._on_event = on_event
+ self._on_error = on_error
+ self._exit_code: int | None = None
+ self._line_buf = ""
+
+ def _parse_lines(self, text: str) -> None:
+ """Parse JSON lines from stdout data."""
+ self._line_buf += text
+ lines = self._line_buf.split("\n")
+ self._line_buf = lines.pop() # Keep incomplete last line
+ for line in lines:
+ trimmed = line.strip()
+ if not trimmed:
+ continue
+ try:
+ data = json.loads(trimmed)
+ event_type = data.pop("type", "unknown")
+ if self._on_event:
+ self._on_event(AgentEvent(type=event_type, data=data))
+ except json.JSONDecodeError:
+ if self._on_error:
+ self._on_error(f"non-JSON stdout: {trimmed}")
+
+ async def collect_events(self) -> list[AgentEvent]:
+ """Collect all events until the process exits.
+
+ Returns:
+ List of all agent events received.
+ """
+ events: list[AgentEvent] = []
+ original_on_event = self._on_event
+
+ def capture(event: AgentEvent) -> None:
+ events.append(event)
+ if original_on_event:
+ original_on_event(event)
+
+ self._on_event = capture
+
+ try:
+ await self.wait()
+ finally:
+ self._on_event = original_on_event
+
+ return events
+
+ async def wait(self) -> int:
+ """Wait for the agent process to exit.
+
+ Returns:
+ The process exit code.
+ """
+ try:
+ async for message in self._ws:
+ if isinstance(message, str):
+ continue
+ if len(message) < 1:
+ continue
+
+ stream_id = message[0]
+ payload = message[1:]
+
+ if stream_id == 0x01: # stdout — JSON lines
+ self._parse_lines(payload.decode("utf-8", errors="replace"))
+ elif stream_id == 0x02: # stderr
+ if self._on_error:
+ self._on_error(payload.decode("utf-8", errors="replace"))
+ elif stream_id == 0x03: # exit
+ if len(payload) >= 4:
+ self._exit_code = struct.unpack(">i", payload[:4])[0]
+ else:
+ self._exit_code = 0
+ break
+ elif stream_id == 0x04: # scrollback_end
+ pass
+ except websockets.ConnectionClosed:
+ if self._exit_code is None:
+ self._exit_code = -1
+
+ # Flush remaining line buffer
+ if self._line_buf.strip():
+ try:
+ data = json.loads(self._line_buf.strip())
+ event_type = data.pop("type", "unknown")
+ if self._on_event:
+ self._on_event(AgentEvent(type=event_type, data=data))
+ except json.JSONDecodeError:
+ if self._on_error:
+ self._on_error(f"non-JSON stdout: {self._line_buf.strip()}")
+ self._line_buf = ""
+
+ return self._exit_code if self._exit_code is not None else -1
+
+ def send_prompt(self, text: str) -> None:
+ """Send a prompt to the agent."""
+ self._send_stdin(json.dumps({"type": "prompt", "text": text}) + "\n")
+
+ def interrupt(self) -> None:
+ """Interrupt the current agent operation."""
+ self._send_stdin(json.dumps({"type": "interrupt"}) + "\n")
+
+ def configure(
+ self,
+ model: str | None = None,
+ system_prompt: str | None = None,
+ allowed_tools: list[str] | None = None,
+ permission_mode: str | None = None,
+ max_turns: int | None = None,
+ cwd: str | None = None,
+ ) -> None:
+ """Reconfigure the agent between turns."""
+ config: dict[str, Any] = {"type": "configure"}
+ if model:
+ config["model"] = model
+ if system_prompt:
+ config["systemPrompt"] = system_prompt
+ if allowed_tools:
+ config["allowedTools"] = allowed_tools
+ if permission_mode:
+ config["permissionMode"] = permission_mode
+ if max_turns is not None:
+ config["maxTurns"] = max_turns
+ if cwd:
+ config["cwd"] = cwd
+ self._send_stdin(json.dumps(config) + "\n")
+
+ async def kill(self, signal: int = 9) -> None:
+ """Kill the agent session."""
+ resp = await self._client.post(
+ f"/sandboxes/{self.sandbox_id}/agent/{self.session_id}/kill",
+ json={"signal": signal},
+ )
+ resp.raise_for_status()
+
+ async def close(self) -> None:
+ """Close the WebSocket connection."""
+ await self._ws.close()
+
+ def _send_stdin(self, data: str) -> None:
+ """Send data to the agent process stdin via WebSocket."""
+ payload = data.encode("utf-8")
+ msg = bytes([0x00]) + payload
+ # websockets library expects awaitable send, but for fire-and-forget
+ # we use the sync path via ensure_future
+ import asyncio
+ asyncio.ensure_future(self._ws.send(msg))
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 9c499435..b2fc466c 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -8,6 +8,7 @@ from typing import Any
import httpx
+from opencomputer.agent import Agent
from opencomputer.exec import Exec
from opencomputer.filesystem import Filesystem
from opencomputer.pty import Pty
@@ -169,6 +170,11 @@ class Sandbox:
)
resp.raise_for_status()
+ @property
+ def agent(self) -> Agent:
+ """Access Claude Agent SDK sessions."""
+ return Agent(self._ops_client, self.sandbox_id, self._connect_url, self._token)
+
@property
def files(self) -> Filesystem:
"""Access filesystem operations."""
diff --git a/sdks/typescript/src/agent.ts b/sdks/typescript/src/agent.ts
new file mode 100644
index 00000000..bb45aa6d
--- /dev/null
+++ b/sdks/typescript/src/agent.ts
@@ -0,0 +1,245 @@
+export interface AgentEvent {
+ type:
+ | "ready"
+ | "configured"
+ | "assistant"
+ | "result"
+ | "system"
+ | "tool_use_summary"
+ | "turn_complete"
+ | "interrupted"
+ | "error"
+ | string;
+ [key: string]: unknown;
+}
+
+export interface McpServerConfig {
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+}
+
+export interface AgentConfig {
+ model?: string;
+ systemPrompt?: string;
+ allowedTools?: string[];
+ permissionMode?: string;
+ maxTurns?: number;
+ cwd?: string;
+ mcpServers?: Record<string, McpServerConfig>;
+}
+
+export interface AgentStartOpts extends AgentConfig {
+ prompt?: string;
+ onEvent?: (event: AgentEvent) => void;
+ onError?: (data: string) => void;
+ onExit?: (exitCode: number) => void;
+ onScrollbackEnd?: () => void;
+}
+
+export interface AgentSession {
+ sessionId: string;
+ done: Promise<number>;
+ sendPrompt(text: string): void;
+ interrupt(): void;
+ configure(config: AgentConfig): void;
+ kill(signal?: number): Promise<void>;
+ close(): void;
+}
+
+export class Agent {
+ 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(opts: AgentStartOpts = {}): Promise<AgentSession> {
+ const body: Record<string, unknown> = {};
+ if (opts.prompt) body.prompt = opts.prompt;
+ if (opts.model) body.model = opts.model;
+ if (opts.systemPrompt) body.systemPrompt = opts.systemPrompt;
+ if (opts.allowedTools) body.allowedTools = opts.allowedTools;
+ if (opts.permissionMode) body.permissionMode = opts.permissionMode;
+ if (opts.maxTurns != null) body.maxTurns = opts.maxTurns;
+ if (opts.cwd) body.cwd = opts.cwd;
+ if (opts.mcpServers) body.mcpServers = opts.mcpServers;
+
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
+ method: "POST",
+ headers: this.headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to create agent session: ${resp.status} ${text}`);
+ }
+
+ const data = await resp.json();
+ const sessionId: string = data.sessionID;
+
+ return this.attach(sessionId, opts);
+ }
+
+ async attach(sessionId: string, opts: Omit<AgentStartOpts, "prompt" | keyof AgentConfig> = {}): Promise<AgentSession> {
+ // Connect via the existing exec session WebSocket endpoint
+ 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";
+
+ let gotExit = false;
+ let resolveDone: (code: number) => void;
+ const done = new Promise<number>((resolve) => { resolveDone = resolve; });
+
+ // Line buffer for JSON-line parsing from stdout
+ let lineBuf = "";
+
+ const parseLines = (text: string) => {
+ lineBuf += text;
+ const lines = lineBuf.split("\n");
+ // Keep incomplete last line in buffer
+ lineBuf = lines.pop() ?? "";
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const event: AgentEvent = JSON.parse(trimmed);
+ opts.onEvent?.(event);
+ } catch {
+ // Not JSON — treat as raw output
+ opts.onError?.(`non-JSON stdout: ${trimmed}`);
+ }
+ }
+ };
+
+ const decoder = new TextDecoder();
+
+ 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 — JSON lines from wrapper
+ parseLines(decoder.decode(payload, { stream: true }));
+ break;
+ case 0x02: // stderr — wrapper's own logs
+ opts.onError?.(decoder.decode(payload, { stream: true }));
+ break;
+ case 0x03: // exit
+ gotExit = true;
+ if (payload.length >= 4) {
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const exitCode = view.getInt32(0, false);
+ opts.onExit?.(exitCode);
+ resolveDone(exitCode);
+ } else {
+ opts.onExit?.(0);
+ resolveDone(0);
+ }
+ break;
+ case 0x04: // scrollback_end
+ opts.onScrollbackEnd?.();
+ break;
+ }
+ };
+
+ ws.onclose = () => {
+ // Flush remaining line buffer
+ if (lineBuf.trim()) {
+ try {
+ const event: AgentEvent = JSON.parse(lineBuf.trim());
+ opts.onEvent?.(event);
+ } catch {
+ opts.onError?.(`non-JSON stdout: ${lineBuf.trim()}`);
+ }
+ lineBuf = "";
+ }
+ if (!gotExit) {
+ opts.onExit?.(-1);
+ resolveDone(-1);
+ }
+ };
+
+ ws.onerror = () => {
+ if (!gotExit) {
+ opts.onExit?.(-1);
+ resolveDone(-1);
+ }
+ };
+
+ const agent = this;
+
+ const sendStdin = (data: string) => {
+ if (ws.readyState !== WebSocket.OPEN) return;
+ const payload = new TextEncoder().encode(data);
+ const msg = new Uint8Array(1 + payload.length);
+ msg[0] = 0x00;
+ msg.set(payload, 1);
+ ws.send(msg);
+ };
+
+ return {
+ sessionId,
+ done,
+ sendPrompt(text: string): void {
+ sendStdin(JSON.stringify({ type: "prompt", text }) + "\n");
+ },
+ interrupt(): void {
+ sendStdin(JSON.stringify({ type: "interrupt" }) + "\n");
+ },
+ configure(config: AgentConfig): void {
+ sendStdin(JSON.stringify({ type: "configure", ...config }) + "\n");
+ },
+ async kill(signal?: number): Promise<void> {
+ const body: Record<string, unknown> = {};
+ if (signal != null) body.signal = signal;
+
+ const resp = await fetch(`${agent.apiUrl}/sandboxes/${agent.sandboxId}/agent/${sessionId}/kill`, {
+ method: "POST",
+ headers: agent.headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to kill agent session: ${resp.status} ${text}`);
+ }
+ },
+ close(): void {
+ ws.close();
+ },
+ };
+ }
+
+ async list(): Promise<Array<{ sessionID: string; sandboxID: string; running: boolean; startedAt: string }>> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
+ headers: this.headers,
+ });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to list agent sessions: ${resp.status}`);
+ }
+
+ return resp.json();
+ }
+}
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index 34007b19..d7f8acaf 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -1,4 +1,5 @@
export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type PatchResult } from "./sandbox.js";
+export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";
export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 1b2ba45d..6c82f5fc 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,3 +1,4 @@
+import { Agent } from "./agent.js";
import { Filesystem } from "./filesystem.js";
import { Exec } from "./exec.js";
import { Pty } from "./pty.js";
@@ -68,6 +69,7 @@ export interface PreviewURLResult {
export class Sandbox {
readonly sandboxId: string;
+ readonly agent: Agent;
readonly files: Filesystem;
readonly exec: Exec;
readonly pty: Pty;
@@ -91,6 +93,7 @@ export class Sandbox {
const opsKey = this.connectUrl ? "" : apiKey;
const opsToken = this.connectUrl ? this.token : "";
+ this.agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
this.files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
this.exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
this.pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
@@ -214,6 +217,7 @@ export class Sandbox {
const opsKey = this.connectUrl ? "" : this.apiKey;
const opsToken = this.connectUrl ? this.token : "";
+ (this as any).agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
(this as any).files = new Filesystem(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);
@@ -295,6 +299,7 @@ export class Sandbox {
const opsUrl = this.connectUrl || this.apiUrl;
const opsKey = this.connectUrl ? "" : this.apiKey;
const opsToken = this.connectUrl ? this.token : "";
+ (this as any).agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
(this as any).files = new Filesystem(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);