An open-source, faster Devin alternative
TypeScript
agent: watch queued operations
Igor Zalutski77e666e6ae1d
diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.goindex d20f20c6..30432cc5 100644--- a/cmd/oc/internal/commands/agent.go+++ b/cmd/oc/internal/commands/agent.go@@ -70,6 +70,7 @@ type agentResponse struct {ID string `json:"id"`DisplayName string `json:"display_name"`Core *string `json:"core"`+ Model *string `json:"model,omitempty"`Channels interface{} `json:"channels"`Packages interface{} `json:"packages"`SecretStore *string `json:"secret_store"`@@ -79,15 +80,55 @@ type agentResponse struct {// Populated by GET /v1/agents/:id (enriched response); omitted by// POST /v1/agents and the list endpoint.- Status *string `json:"status,omitempty"`- InstanceID *string `json:"instance_id,omitempty"`- LastError *LastError `json:"last_error,omitempty"`+ Status *string `json:"status,omitempty"`+ InstanceID *string `json:"instance_id,omitempty"`+ InstanceStatus *string `json:"instance_status,omitempty"`+ CoreStatus map[string]interface{} `json:"core_status,omitempty"`+ ChannelStatus map[string]map[string]any `json:"channel_status,omitempty"`+ PackageStatus map[string]map[string]any `json:"package_status,omitempty"`+ CurrentOperation *AgentOperation `json:"current_operation,omitempty"`+ Conditions []AgentCondition `json:"conditions,omitempty"`+ LastError *LastError `json:"last_error,omitempty"`}type agentListResponse struct {Agents []agentResponse `json:"agents"`}+type AgentOperation struct {+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ InstanceID *string `json:"instance_id,omitempty"`+ Kind string `json:"kind"`+ TargetType *string `json:"target_type,omitempty"`+ TargetKey *string `json:"target_key,omitempty"`+ Status string `json:"status"`+ Phase *string `json:"phase,omitempty"`+ Code *string `json:"code,omitempty"`+ Message *string `json:"message,omitempty"`+ CreatedBy *string `json:"created_by,omitempty"`+ StartedAt *string `json:"started_at,omitempty"`+ CompletedAt *string `json:"completed_at,omitempty"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++type AgentCondition struct {+ Type string `json:"type"`+ Subject string `json:"subject,omitempty"`+ Status string `json:"status"`+ Reason string `json:"reason"`+ Message string `json:"message,omitempty"`+}++type operationSubmissionResponse struct {+ AgentID string `json:"agent_id"`+ Status string `json:"status"`+ Channel string `json:"channel,omitempty"`+ Package string `json:"package,omitempty"`+ Operation *AgentOperation `json:"operation,omitempty"`+}+// ── Parent command ──var agentCmd = &cobra.Command{@@ -150,6 +191,7 @@ func init() {agentCreateCmd.Flags().Bool("no-wait", false, "Don't wait for instance provisioning; exit after agent record is created")agentConnectCmd.Flags().String("bot-token", "", "Telegram bot token (required for channel=telegram when stdin is not a TTY)")+ agentConnectCmd.Flags().Bool("no-wait", false, "Don't wait for channel orchestration to finish")agentInstallCmd.Flags().Bool("no-wait", false, "Don't wait for install orchestration to finish")diff --git a/cmd/oc/internal/commands/agent_connect.go b/cmd/oc/internal/commands/agent_connect.goindex 41a507f6..cdc15575 100644--- a/cmd/oc/internal/commands/agent_connect.go+++ b/cmd/oc/internal/commands/agent_connect.go@@ -26,6 +26,7 @@ var agentConnectCmd = &cobra.Command{agentID := args[0]channel := args[1]+ noWait, _ := cmd.Flags().GetBool("no-wait")body := map[string]interface{}{}@@ -55,11 +56,37 @@ var agentConnectCmd = &cobra.Command{body["bot_token"] = token}- var result map[string]interface{}+ if !jsonOutput {+ fmt.Fprintf(os.Stderr, "Connecting %s to %s\n", channel, agentID)+ }++ var result operationSubmissionResponseif err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel, body, &result); err != nil {return err}+ if noWait || result.Operation == nil {+ note := ""+ if result.Operation != nil {+ note = "Operation: " + result.Operation.ID+ }+ renderAsyncFallback(os.Stdout, jsonOutput, agentID, channel+" connect", note)+ return nil+ }++ agent, err := waitForOperation(cmd, sc, agentID, result.Operation, channel+" connect")+ if err != nil {+ return err+ }+ if agent == nil {+ return nil+ }++ if jsonOutput {+ printer.Print(agent, func() {})+ return nil+ }+fmt.Printf("%s connected to %s.\n", channel, agentID)if channel == "telegram" {fmt.Println("Message your bot on Telegram to start chatting.")diff --git a/cmd/oc/internal/commands/agent_create.go b/cmd/oc/internal/commands/agent_create.goindex 66866a0c..2f15d661 100644--- a/cmd/oc/internal/commands/agent_create.go+++ b/cmd/oc/internal/commands/agent_create.go@@ -2,12 +2,9 @@ package commandsimport ("fmt"+ "github.com/spf13/cobra""os""strings"- "time"-- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"- "github.com/spf13/cobra")var agentCreateCmd = &cobra.Command{@@ -64,104 +61,28 @@ var agentCreateCmd = &cobra.Command{// --no-wait short-circuits into Mode 3 (async fallback). Scripts// that don't want to block use this path.if noWait {- renderAsyncFallback(os.Stdout, jsonOutput, id, "Instance provisioning", "")+ note := ""+ if agent.CurrentOperation != nil {+ note = "Operation: " + agent.CurrentOperation.ID+ }+ renderAsyncFallback(os.Stdout, jsonOutput, id, "Instance provisioning", note)return nil}- return pollUntilTerminal(cmd, sc, id, "Instance creation")- },-}--// ── Polling ──--// Poll cadence for async operations. 2s is fast enough that humans don't-// notice, slow enough not to hammer the API. The 180s cap is a generous-// bound on "it's almost certainly still working" before falling back to-// the async message.-const (- pollInterval = 2 * time.Second- pollTimeout = 180 * time.Second-)--// pollUntilTerminal polls GET /v1/agents/:id until status reaches a terminal-// state (running / error), the deadline hits, or a persistent network error-// occurs. One of three Mode outcomes results:-// - Mode 1 (running): success block, exit 0-// - Mode 2 (error): error block, ExitError with class-based code-// - Mode 3 (timeout / err): async-fallback message, exit 0-//-// See ws-gstack/work/agent-error-visibility.md — "Three outcome modes".-func pollUntilTerminal(cmd *cobra.Command, sc *client.Client, agentID, op string) error {- deadline := time.Now().Add(pollTimeout)-- // Print phase progress only in text mode. JSON mode suppresses stderr- // progress so consumers get exactly one object on stdout.- printProgress := func(phase string) {- if !jsonOutput {- fmt.Fprintf(os.Stderr, " ⋯ %s\n", phase)- }- }-- lastPhase := ""- consecutiveErrors := 0- const errorThreshold = 3 // tolerate transient blips before declaring the poll dead-- for time.Now().Before(deadline) {- time.Sleep(pollInterval)-- var agent agentResponse- if err := sc.Get(cmd.Context(), "/v1/agents/"+agentID, &agent); err != nil {- consecutiveErrors++- if consecutiveErrors >= errorThreshold {- // Poll lost connection; Mode 3 fallback. Work may still be- // running in sessions-api — the user just can't observe it- // from here.- renderAsyncFallback(os.Stdout, jsonOutput, agentID, op+" still in progress", "")- return nil- }- continue+ if agent.CurrentOperation == nil {+ printer.Print(agent, func() {})+ return nil}- consecutiveErrors = 0- status := ""- if agent.Status != nil {- status = *agent.Status+ finalAgent, err := waitForOperation(cmd, sc, id, agent.CurrentOperation, "Instance creation")+ if err != nil {+ return err}-- switch status {- case "running":- // Mode 1 — success.- if !jsonOutput {- fmt.Fprintln(os.Stderr, " ✓ Ready")- }- printer.Print(agent, func() {})+ if finalAgent == nil {return nil-- case "error":- // Mode 2 — failure. Render the error block and exit with the- // class-mapped code.- if !jsonOutput {- fmt.Fprintln(os.Stderr, " ✗ "+op+" failed")- fmt.Fprintln(os.Stderr)- RenderLastError(os.Stderr, agent.LastError)- } else {- printer.Print(agent, func() {})- }- return &ExitError{Code: ExitCodeFor(agent.LastError)}-- case "creating", "":- // Still working. Report phase progress from packageStatus /- // channelStatus in a future pass; for now the instance status- // alone is enough to reassure the user something's happening.- phase := "Provisioning instance"- if phase != lastPhase {- printProgress(phase)- lastPhase = phase- }}- }- // Mode 3 — poll hit the cap. Work is likely still running.- renderAsyncFallback(os.Stdout, jsonOutput, agentID, op+" still in progress", "")- return nil+ printer.Print(finalAgent, func() {})+ return nil+ },}diff --git a/cmd/oc/internal/commands/agent_errors.go b/cmd/oc/internal/commands/agent_errors.goindex 945eba95..97c268f5 100644--- a/cmd/oc/internal/commands/agent_errors.go+++ b/cmd/oc/internal/commands/agent_errors.go@@ -65,6 +65,32 @@ var codeCatalog = map[string]struct {class: classUpstream4xx,suggestion: "Telegram rejected the bot token. Verify the token at https://t.me/BotFather.",},+ "webhook_register_failed": {+ class: classGeneral,+ suggestion: "Telegram webhook registration failed.\n" ++ "Verify the bot token and retry. If it persists, inspect agent events\n" ++ "for the upstream Telegram response.",+ },+ "secret_store_failed": {+ class: classGeneral,+ suggestion: "The platform could not write channel or package secrets to OC.\n" ++ "Retry once. If it persists, inspect OC secret-store health and permissions.",+ },+ "core_not_ready": {+ class: classTransient,+ suggestion: "The managed core did not become healthy in time.\n" ++ "Retry once the agent is healthy, or inspect `oc agent get <id>` for readiness details.",+ },+ "channel_not_ready": {+ class: classTransient,+ suggestion: "The channel listener did not become ready in time.\n" ++ "Retry once the agent is healthy, or inspect `oc agent get <id>` for channel readiness.",+ },+ "package_verify_failed": {+ class: classGeneral,+ suggestion: "The package did not pass its verification step.\n" ++ "Inspect the package phase in agent events and retry after fixing the underlying issue.",+ },"sandbox_provision_timeout": {class: classTransient,suggestion: "Sandbox provisioning timed out. The OC worker may be unhealthy.\n" +@@ -154,7 +180,7 @@ func renderAsyncFallback(stdoutW io.Writer, jsonOut bool, id, op, note string) {enc.SetIndent("", " ")_ = enc.Encode(asyncFallback{ID: id,- Status: "creating",+ Status: "starting",Async: true,CheckWith: "oc agent get " + id,Note: note,@@ -162,7 +188,7 @@ func renderAsyncFallback(stdoutW io.Writer, jsonOut bool, id, op, note string) {return}- fmt.Fprintf(stdoutW, " ⋯ %s in background (typically 30-60s).\n", op)+ fmt.Fprintf(stdoutW, " ⋯ %s in background.\n", op)if note != "" {fmt.Fprintf(stdoutW, " %s\n", note)}diff --git a/cmd/oc/internal/commands/agent_get.go b/cmd/oc/internal/commands/agent_get.goindex 1ad29e17..a983fc2c 100644--- a/cmd/oc/internal/commands/agent_get.go+++ b/cmd/oc/internal/commands/agent_get.go@@ -3,6 +3,7 @@ package commandsimport ("fmt""os"+ "strings""github.com/spf13/cobra")@@ -35,10 +36,34 @@ var agentGetCmd = &cobra.Command{if agent.Status != nil {fmt.Printf("Status: %s\n", *agent.Status)}+ if agent.InstanceStatus != nil {+ fmt.Printf("Instance: %s\n", *agent.InstanceStatus)+ }+ if agent.CurrentOperation != nil {+ fmt.Printf("Op: %s (%s)\n", humanizePhase(agent.CurrentOperation.Kind), agent.CurrentOperation.Status)+ if progress := operationProgress(*agent.CurrentOperation); progress != "" {+ fmt.Printf("Progress: %s\n", progress)+ }+ }fmt.Printf("Channels: %s\n", formatList(agent.Channels))fmt.Printf("Packages: %s\n", formatList(agent.Packages))fmt.Printf("Created: %s\n", agent.CreatedAt)+ if pending := pendingConditions(agent.Conditions); len(pending) > 0 {+ fmt.Println("Conditions:")+ for _, cond := range pending {+ label := cond.Type+ if cond.Subject != "" {+ label += "[" + cond.Subject + "]"+ }+ line := fmt.Sprintf(" %s=%s (%s)", label, cond.Status, cond.Reason)+ if msg := strings.TrimSpace(cond.Message); msg != "" {+ line += ": " + msg+ }+ fmt.Println(line)+ }+ }+if agent.LastError != nil {fmt.Println()RenderLastError(os.Stdout, agent.LastError)@@ -48,3 +73,13 @@ var agentGetCmd = &cobra.Command{return nil},}++func pendingConditions(conditions []AgentCondition) []AgentCondition {+ var pending []AgentCondition+ for _, cond := range conditions {+ if cond.Status != "True" {+ pending = append(pending, cond)+ }+ }+ return pending+}diff --git a/cmd/oc/internal/commands/agent_operations.go b/cmd/oc/internal/commands/agent_operations.gonew file mode 100644index 00000000..300c8d0c--- /dev/null+++ b/cmd/oc/internal/commands/agent_operations.go@@ -0,0 +1,168 @@+package commands++import (+ "fmt"+ "os"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++const (+ pollInterval = 2 * time.Second+ pollTimeout = 180 * time.Second+)++func waitForOperation(+ cmd *cobra.Command,+ sc *client.Client,+ agentID string,+ operation *AgentOperation,+ opLabel string,+) (*agentResponse, error) {+ if operation == nil {+ return nil, fmt.Errorf("%s did not return an operation handle", opLabel)+ }++ deadline := time.Now().Add(pollTimeout)+ lastProgress := ""+ consecutiveErrors := 0+ const errorThreshold = 3++ printProgress := func(progress string) {+ if !jsonOutput && progress != "" {+ fmt.Fprintf(os.Stderr, " ⋯ %s\n", progress)+ }+ }++ if progress := operationProgress(*operation); progress != "" {+ printProgress(progress)+ lastProgress = progress+ }++ for time.Now().Before(deadline) {+ time.Sleep(pollInterval)++ current, err := fetchOperation(cmd, sc, agentID, operation.ID)+ if err != nil {+ consecutiveErrors+++ if consecutiveErrors >= errorThreshold {+ renderAsyncFallback(os.Stdout, jsonOutput, agentID, opLabel+" still in progress", lastProgress)+ return nil, nil+ }+ continue+ }+ consecutiveErrors = 0++ progress := operationProgress(current)+ if progress != "" && progress != lastProgress {+ printProgress(progress)+ lastProgress = progress+ }++ switch current.Status {+ case "queued", "running":+ continue+ case "succeeded":+ agent, err := fetchAgent(cmd, sc, agentID)+ if err != nil {+ return nil, fmt.Errorf("%s completed but failed to fetch agent state: %w", opLabel, err)+ }+ return agent, nil+ case "failed", "canceled":+ agent, err := fetchAgent(cmd, sc, agentID)+ if err != nil {+ return nil, fmt.Errorf("%s failed (unable to fetch agent state: %w)", opLabel, err)+ }+ lastErr := effectiveLastError(agent, ¤t)+ if !jsonOutput {+ fmt.Fprintln(os.Stderr, " ✗ "+opLabel+" failed")+ fmt.Fprintln(os.Stderr)+ RenderLastError(os.Stderr, lastErr)+ } else {+ agent.LastError = lastErr+ printer.Print(agent, func() {})+ }+ return nil, &ExitError{Code: ExitCodeFor(lastErr)}+ default:+ continue+ }+ }++ renderAsyncFallback(os.Stdout, jsonOutput, agentID, opLabel+" still in progress", lastProgress)+ return nil, nil+}++func fetchAgent(cmd *cobra.Command, sc *client.Client, agentID string) (*agentResponse, error) {+ var agent agentResponse+ if err := sc.Get(cmd.Context(), "/v1/agents/"+agentID, &agent); err != nil {+ return nil, err+ }+ return &agent, nil+}++func fetchOperation(cmd *cobra.Command, sc *client.Client, agentID, operationID string) (AgentOperation, error) {+ var operation AgentOperation+ err := sc.Get(cmd.Context(), "/v1/agents/"+agentID+"/operations/"+operationID, &operation)+ return operation, err+}++func effectiveLastError(agent *agentResponse, operation *AgentOperation) *LastError {+ if agent != nil && agent.LastError != nil {+ return agent.LastError+ }+ if operation == nil {+ return nil+ }++ phase := ""+ if operation.Phase != nil {+ phase = *operation.Phase+ }+ message := operationProgress(*operation)+ code := ""+ if operation.Code != nil {+ code = *operation.Code+ }+ at := operation.UpdatedAt+ if operation.CompletedAt != nil && *operation.CompletedAt != "" {+ at = *operation.CompletedAt+ }++ return &LastError{+ Phase: phase,+ Message: message,+ Code: code,+ At: at,+ }+}++func operationProgress(operation AgentOperation) string {+ if operation.Message != nil {+ if trimmed := strings.TrimSpace(*operation.Message); trimmed != "" {+ return trimmed+ }+ }+ if operation.Phase != nil {+ if trimmed := strings.TrimSpace(*operation.Phase); trimmed != "" {+ return humanizePhase(trimmed)+ }+ }+ return humanizePhase(operation.Kind)+}++func humanizePhase(value string) string {+ if value == "" {+ return ""+ }+ parts := strings.Split(value, "_")+ for i, part := range parts {+ if part == "" {+ continue+ }+ parts[i] = strings.ToUpper(part[:1]) + part[1:]+ }+ return strings.Join(parts, " ")+}diff --git a/cmd/oc/internal/commands/agent_packages.go b/cmd/oc/internal/commands/agent_packages.goindex ce0cec16..49e90de9 100644--- a/cmd/oc/internal/commands/agent_packages.go+++ b/cmd/oc/internal/commands/agent_packages.go@@ -1,15 +1,12 @@package commands-// Package lifecycle: install, uninstall, list. Install is the only one that-// goes through the error-visibility render path — orchestration runs-// synchronously in sessions-api, so a 500 from the POST means we can fetch-// the just-persisted last_error and render the block.+// Package lifecycle: install, uninstall, list. Install is queued and watched+// via agent operation resources.import ("fmt""os"- "github.com/opensandbox/opensandbox/cmd/oc/internal/client""github.com/spf13/cobra")@@ -31,31 +28,35 @@ var agentInstallCmd = &cobra.Command{fmt.Fprintf(os.Stderr, "Installing %s on %s\n", pkg, agentID)}- // sessions-api returns 500 when install orchestration fails- // synchronously. A successful 200 means the whole flow completed.- // The orchestrator writes per-phase events to agent_events; we- // surface them by re-fetching and rendering last_error on error.- var result map[string]interface{}- postErr := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/packages/"+pkg, nil, &result)+ var result operationSubmissionResponse+ if err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/packages/"+pkg, nil, &result); err != nil {+ return err+ }- if postErr == nil {- if !jsonOutput {- fmt.Fprintf(os.Stderr, " ✓ %s installed\n", pkg)- }- if jsonOutput {- printer.PrintJSON(result)+ if noWait {+ note := ""+ if result.Operation != nil {+ note = "Operation: " + result.Operation.ID}+ renderAsyncFallback(os.Stdout, jsonOutput, agentID, "Package install", note)return nil}- // 500 from the orchestrator — the event is already written. --no-wait- // callers get the async fallback because they opted out of waiting;- // otherwise fetch the latest state to render the error block.- if noWait {- renderAsyncFallback(os.Stdout, jsonOutput, agentID, "Package install", postErr.Error())+ agent, err := waitForOperation(cmd, sc, agentID, result.Operation, "Package install")+ if err != nil {+ return err+ }+ if agent == nil {return nil}- return renderAgentError(cmd, sc, agentID, "Install")++ if jsonOutput {+ printer.Print(agent, func() {})+ return nil+ }++ fmt.Fprintf(os.Stderr, " ✓ %s installed\n", pkg)+ return nil},}@@ -108,28 +109,3 @@ var agentPackagesCmd = &cobra.Command{return nil},}--// renderAgentError fetches the current agent state and renders the last_error-// block. Used by synchronous failure paths (install) where the POST returned-// 500 and the orchestrator has already persisted an error event. If the fetch-// itself fails we return the original network error so the user sees-// something rather than nothing.-func renderAgentError(cmd *cobra.Command, sc *client.Client, agentID, op string) error {- var agent agentResponse- if err := sc.Get(cmd.Context(), "/v1/agents/"+agentID, &agent); err != nil {- return fmt.Errorf("%s failed (unable to fetch agent state: %w)", op, err)- }- if agent.LastError == nil {- // 500 without an event row shouldn't happen post-migration, but guard- // against it so the user isn't told "everything's fine" after a 500.- return fmt.Errorf("%s failed (no error detail available — check server logs)", op)- }- if !jsonOutput {- fmt.Fprintln(os.Stderr, " ✗ "+op+" failed")- fmt.Fprintln(os.Stderr)- RenderLastError(os.Stderr, agent.LastError)- } else {- printer.Print(agent, func() {})- }- return &ExitError{Code: ExitCodeFor(agent.LastError)}-}