An open-source, faster Devin alternative
TypeScript
Add synchronous POST /exec/run endpoint for exec.run()
motatoes047aebcbfb1a
diff --git a/cmd/oc/internal/commands/exec.go b/cmd/oc/internal/commands/exec.goindex 7a5f0e58..3c54c38e 100644--- a/cmd/oc/internal/commands/exec.go+++ b/cmd/oc/internal/commands/exec.go@@ -45,7 +45,38 @@ Subcommands:envSlice, _ := cmd.Flags().GetStringSlice("env")wait, _ := cmd.Flags().GetBool("wait")- // Create exec session+ if wait {+ // Wait mode: use exec/run endpoint for synchronous execution+ req := types.ProcessConfig{+ Command: command,+ Args: cmdArgs,+ Cwd: cwd,+ Timeout: timeout,+ Env: parseKVSlice(envSlice),+ }++ var result types.ProcessResult+ if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec/run", req, &result); err != nil {+ return err+ }++ if jsonOutput {+ printer.PrintJSON(result)+ } else {+ if result.Stdout != "" {+ fmt.Print(result.Stdout)+ }+ if result.Stderr != "" {+ fmt.Fprint(os.Stderr, result.Stderr)+ }+ if result.ExitCode != 0 {+ os.Exit(result.ExitCode)+ }+ }+ return nil+ }++ // Non-wait mode: create exec sessionreq := types.ExecSessionCreateRequest{Command: command,Args: cmdArgs,@@ -59,53 +90,13 @@ Subcommands: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- }+ 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},}diff --git a/internal/api/exec_session.go b/internal/api/exec_session.goindex 8dd8a6a7..74a252a0 100644--- a/internal/api/exec_session.go+++ b/internal/api/exec_session.go@@ -205,6 +205,47 @@ func (s *Server) execSessionWebSocket(c echo.Context) error {}}+func (s *Server) execRun(c echo.Context) error {+ id := c.Param("id")++ var req types.ProcessConfig+ 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 result *types.ProcessResult++ routeOp := func(ctx context.Context) error {+ var err error+ result, err = s.manager.Exec(ctx, id, req)+ return err+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "execRun", 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.StatusOK, result)+}+func (s *Server) killExecSession(c echo.Context) error {if s.execSessionManager == nil {return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)diff --git a/internal/api/router.go b/internal/api/router.goindex 4e3518c0..0474f7a6 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -160,6 +160,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/sandboxes/:id/exec", s.listExecSessions)api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)+ api.POST("/sandboxes/:id/exec/run", s.execRun)// Filesystemapi.GET("/sandboxes/:id/files", s.readFile)diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex b2fac43c..459014cd 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -238,6 +238,38 @@ func (s *HTTPServer) execSessionWebSocket(c echo.Context) error {}}+func (s *HTTPServer) execRun(c echo.Context) error {+ id := c.Param("id")++ var req types.ProcessConfig+ 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 result *types.ProcessResult++ routeOp := func(ctx context.Context) error {+ var err error+ result, err = s.manager.Exec(ctx, id, req)+ return err+ }++ if s.router != nil {+ if err := s.router.Route(c.Request().Context(), id, "execRun", 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.StatusOK, result)+}+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"})diff --git a/internal/worker/http_server.go b/internal/worker/http_server.goindex 19ea1b9a..d5be8ca5 100644--- a/internal/worker/http_server.go+++ b/internal/worker/http_server.go@@ -86,6 +86,7 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sanapi.GET("/sandboxes/:id/exec", s.listExecSessions)api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)+ api.POST("/sandboxes/:id/exec/run", s.execRun)// Timeoutapi.POST("/sandboxes/:id/timeout", s.setTimeout)diff --git a/sdks/python/opencomputer/exec.py b/sdks/python/opencomputer/exec.pyindex 5f3449d8..6cc78c46 100644--- a/sdks/python/opencomputer/exec.py+++ b/sdks/python/opencomputer/exec.py@@ -2,12 +2,10 @@from __future__ import annotations-import structfrom dataclasses import dataclassfrom typing import Anyimport httpx-import websockets@dataclass@@ -60,59 +58,23 @@ class Exec: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]}+ body: dict[str, Any] = {"cmd": "sh", "args": ["-c", command], "timeout": timeout}if env:body["envs"] = envif cwd:body["cwd"] = cwd- if timeout:- body["timeout"] = timeoutresp = await self._client.post(- f"/sandboxes/{self._sandbox_id}/exec",+ f"/sandboxes/{self._sandbox_id}/exec/run",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- passreturn 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"),+ exit_code=data["exitCode"],+ stdout=data.get("stdout", ""),+ stderr=data.get("stderr", ""),)async def start(diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.tsindex 9d919bce..fa4f59a2 100644--- a/sdks/typescript/src/exec.ts+++ b/sdks/typescript/src/exec.ts@@ -208,37 +208,26 @@ export class Exec {}async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {- let stdout = "";- let stderr = "";- const timeout = opts.timeout ?? 60;-- return new Promise<ProcessResult>((resolve, reject) => {- const decoder = new TextDecoder();- let resolved = false;-- this.start("sh", {- args: ["-c", command],- env: opts.env,- cwd: opts.cwd,- timeout,- onStdout: (data) => {- stdout += decoder.decode(data, { stream: true });- },- onStderr: (data) => {- stderr += decoder.decode(data, { stream: true });- },- onExit: (exitCode) => {- if (!resolved) {- resolved = true;- resolve({ exitCode, stdout, stderr });- }- },- }).catch((err) => {- if (!resolved) {- resolved = true;- reject(err);- }- });+ const body: Record<string, unknown> = {+ cmd: "sh",+ args: ["-c", command],+ };+ if (opts.env) body.envs = opts.env;+ if (opts.cwd) body.cwd = opts.cwd;+ if (opts.timeout != null) body.timeout = opts.timeout;+ else body.timeout = 60;++ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run`, {+ method: "POST",+ headers: this.headers,+ body: JSON.stringify(body),});++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to run command: ${resp.status} ${text}`);+ }++ return resp.json();}}