Skip to content

An open-source, faster Devin alternative

TypeScript

feat(oc): agent send/chat CLI commands + entitlement preflight

motatoesa1dfa4f3c278
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
index cbf6d0ed..98461b97 100644
--- a/cmd/oc/internal/client/client.go
+++ b/cmd/oc/internal/client/client.go
@@ -170,6 +170,29 @@ func (c *Client) Post(ctx context.Context, path string, body, result interface{}
return nil
}
+// PostStream performs a POST request and returns the raw response so the
+// caller can stream chunks (e.g. SSE / chat-completions). Caller is
+// responsible for closing resp.Body.
+func (c *Client) PostStream(ctx context.Context, path string, body interface{}) (*http.Response, error) {
+ var bodyReader io.Reader
+ if body != nil {
+ data, err := json.Marshal(body)
+ if err != nil {
+ return nil, err
+ }
+ bodyReader = bytes.NewReader(data)
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, bodyReader)
+ if err != nil {
+ return nil, err
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ req.Header.Set("Accept", "text/event-stream")
+ return c.do(req)
+}
+
// Put performs a PUT request with a raw body.
func (c *Client) Put(ctx context.Context, path string, body io.Reader) error {
req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, body)
diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.go
index bcbb67d7..b5acabc9 100644
--- a/cmd/oc/internal/commands/agent.go
+++ b/cmd/oc/internal/commands/agent.go
@@ -234,4 +234,6 @@ func init() {
agentCmd.AddCommand(agentUninstallCmd)
agentCmd.AddCommand(agentPackagesCmd)
agentCmd.AddCommand(agentEventsCmd)
+ agentCmd.AddCommand(agentSendCmd)
+ agentCmd.AddCommand(agentChatCmd)
}
diff --git a/cmd/oc/internal/commands/agent_chat.go b/cmd/oc/internal/commands/agent_chat.go
new file mode 100644
index 00000000..e0f834fa
--- /dev/null
+++ b/cmd/oc/internal/commands/agent_chat.go
@@ -0,0 +1,237 @@
+package commands
+
+// `oc agent send` (one-shot) and `oc agent chat` (interactive REPL).
+//
+// Both stream the SSE response from sessions-api's instance-message endpoint
+// (POST /v1/agents/:id/instances/:instId/messages) chunk-by-chunk. The
+// endpoint emits OpenAI-style frames: data: {"type":"text","content":"..."}
+// per chunk, and data: {"type":"done"} on the last frame.
+//
+// `chat` keeps the full message history in memory and resends it every turn
+// — OpenClaw's chat-completions is stateless, so context only persists if
+// the client supplies it.
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+)
+
+type chatTurn struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+}
+
+// resolveAgentInstance fetches the agent and returns its current instance
+// ID. Returns a friendly error when the agent has no running instance.
+func resolveAgentInstance(ctx context.Context, sc *client.Client, agentID string) (string, error) {
+ var agent agentResponse
+ if err := sc.Get(ctx, "/v1/agents/"+agentID, &agent); err != nil {
+ return "", err
+ }
+ if agent.InstanceID == nil || *agent.InstanceID == "" {
+ return "", fmt.Errorf("agent %s has no running instance yet (status=%s) — wait for it to come up and retry",
+ agentID, derefOrDash(agent.Status))
+ }
+ return *agent.InstanceID, nil
+}
+
+func derefOrDash(s *string) string {
+ if s == nil {
+ return "-"
+ }
+ return *s
+}
+
+// streamChatTurn posts to /messages and prints text chunks as they arrive.
+// Returns the assembled assistant text so callers can append it to a
+// running history (used by `oc agent chat`).
+func streamChatTurn(
+ ctx context.Context,
+ sc *client.Client,
+ agentID, instanceID string,
+ history []chatTurn,
+ w io.Writer,
+) (string, error) {
+ body := map[string]interface{}{
+ "messages": history,
+ }
+ resp, err := sc.PostStream(ctx, "/v1/agents/"+agentID+"/instances/"+instanceID+"/messages", body)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ buf, _ := io.ReadAll(resp.Body)
+ return "", fmt.Errorf("chat failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))
+ }
+
+ var assembled strings.Builder
+ reader := bufio.NewReader(resp.Body)
+ for {
+ line, err := reader.ReadString('\n')
+ if line != "" {
+ line = strings.TrimRight(line, "\r\n")
+ if !strings.HasPrefix(line, "data:") {
+ if err == io.EOF {
+ break
+ }
+ continue
+ }
+ payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
+ if payload == "" || payload == "[DONE]" {
+ if err == io.EOF {
+ break
+ }
+ continue
+ }
+ var ev struct {
+ Type string `json:"type"`
+ Content string `json:"content"`
+ Message string `json:"message"`
+ Code string `json:"code"`
+ }
+ if jerr := json.Unmarshal([]byte(payload), &ev); jerr != nil {
+ if err == io.EOF {
+ break
+ }
+ continue
+ }
+ switch ev.Type {
+ case "text":
+ if ev.Content != "" {
+ assembled.WriteString(ev.Content)
+ _, _ = io.WriteString(w, ev.Content)
+ }
+ case "error":
+ return assembled.String(), fmt.Errorf("agent error: %s (%s)", ev.Message, ev.Code)
+ case "done":
+ return assembled.String(), nil
+ }
+ }
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return assembled.String(), err
+ }
+ }
+ return assembled.String(), nil
+}
+
+var agentSendCmd = &cobra.Command{
+ Use: "send <agent-id> <message>",
+ Short: "Send one message to an agent and stream the reply",
+ Long: "Send a single message to an agent and stream the reply to stdout.\n" +
+ "Convenient for smoke-testing core/gateway changes from a shell:\n\n" +
+ " oc agent send my-bot 'hello'\n" +
+ " echo 'translate this to french: hello' | oc agent send my-bot",
+ Args: cobra.RangeArgs(1, 2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ sc, err := sessionsClient(cmd)
+ if err != nil {
+ return err
+ }
+ agentID := args[0]
+
+ var message string
+ if len(args) >= 2 {
+ message = args[1]
+ } else if !stdinIsTTY() {
+ buf, rerr := io.ReadAll(os.Stdin)
+ if rerr != nil {
+ return rerr
+ }
+ message = strings.TrimRight(string(buf), "\n")
+ }
+ if strings.TrimSpace(message) == "" {
+ return fmt.Errorf("message is required (positional arg or piped stdin)")
+ }
+
+ instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)
+ if err != nil {
+ return err
+ }
+
+ history := []chatTurn{{Role: "user", Content: message}}
+ _, err = streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)
+ // Trailing newline so shell prompts return cleanly.
+ fmt.Println()
+ return err
+ },
+}
+
+var agentChatCmd = &cobra.Command{
+ Use: "chat <agent-id>",
+ Short: "Open an interactive chat with an agent",
+ Long: "Open an interactive REPL chat with an agent. Each turn streams\n" +
+ "the assistant reply live. Type ':exit' or send EOF (Ctrl-D) to quit.\n" +
+ "History is kept client-side and resent every turn (OpenClaw's chat-\n" +
+ "completions is stateless).",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ sc, err := sessionsClient(cmd)
+ if err != nil {
+ return err
+ }
+ agentID := args[0]
+
+ instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)
+ if err != nil {
+ return err
+ }
+
+ fmt.Fprintf(os.Stderr, "Chat with %s — type ':exit' or Ctrl-D to quit.\n\n", agentID)
+
+ history := []chatTurn{}
+ reader := bufio.NewReader(os.Stdin)
+ for {
+ fmt.Fprint(os.Stderr, "you> ")
+ line, rerr := reader.ReadString('\n')
+ if rerr == io.EOF {
+ if strings.TrimSpace(line) == "" {
+ fmt.Fprintln(os.Stderr)
+ return nil
+ }
+ } else if rerr != nil {
+ return rerr
+ }
+ msg := strings.TrimRight(line, "\r\n")
+ if strings.TrimSpace(msg) == "" {
+ if rerr == io.EOF {
+ return nil
+ }
+ continue
+ }
+ if msg == ":exit" || msg == ":quit" {
+ return nil
+ }
+
+ history = append(history, chatTurn{Role: "user", Content: msg})
+ fmt.Fprint(os.Stderr, "bot> ")
+ reply, serr := streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)
+ fmt.Println()
+ if serr != nil {
+ // Drop the unanswered user turn so the next try doesn't
+ // re-send the failed pair as context.
+ history = history[:len(history)-1]
+ fmt.Fprintf(os.Stderr, " error: %v\n", serr)
+ continue
+ }
+ history = append(history, chatTurn{Role: "assistant", Content: reply})
+
+ if rerr == io.EOF {
+ return nil
+ }
+ }
+ },
+}
diff --git a/cmd/oc/internal/commands/agent_connect.go b/cmd/oc/internal/commands/agent_connect.go
index 9f3bac34..a05c45e1 100644
--- a/cmd/oc/internal/commands/agent_connect.go
+++ b/cmd/oc/internal/commands/agent_connect.go
@@ -47,6 +47,36 @@ var agentConnectCmd = &cobra.Command{
body := map[string]interface{}{}
if channel == "telegram" {
+ // Pre-flight entitlement check — bail with a clean upgrade
+ // message before asking for a bot token if the agent isn't
+ // subscribed. The actual connect endpoint also gates, but
+ // hitting that path first means the user has to paste a token
+ // just to see the paywall, which is jarring.
+ var ent struct {
+ Entitled bool `json:"entitled"`
+ Reason string `json:"reason"`
+ PriceMonthlyCents int64 `json:"price_monthly_cents"`
+ }
+ err := sc.Get(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel+"/entitlement", &ent)
+ if err != nil {
+ if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {
+ upgradeURL := dashboardAgentURL(cmd, agentID)
+ price := "$20/mo"
+ if ent.PriceMonthlyCents > 0 {
+ price = fmt.Sprintf("$%.2f/mo", float64(ent.PriceMonthlyCents)/100)
+ }
+ fmt.Fprintf(os.Stderr,
+ "\nThis agent isn't subscribed to %s yet (%s per agent).\n"+
+ "Subscribe in the dashboard, then re-run this command:\n\n"+
+ " %s\n\n",
+ channel, price, upgradeURL,
+ )
+ return fmt.Errorf("subscription required for %s on %s", channel, agentID)
+ }
+ // Soft-fail on other lookup errors — fall through to the
+ // real connect, which will surface a more specific error.
+ }
+
token, _ := cmd.Flags().GetString("bot-token")
if token == "" {
if !stdinIsTTY() {
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
index 8cf3425f..b49f8ee7 100644
--- a/web/src/pages/Agents.tsx
+++ b/web/src/pages/Agents.tsx
@@ -74,7 +74,7 @@ export default function Agents() {
<div>
<h1 style={{ fontSize: 22, margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700 }}>Agents</h1>
<p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 6 }}>
- Managed agent runtimes (Hermes, OpenClaw). Add channels and packages to extend what they do.
+ Managed agent runtimes powered by OpenClaw. Add channels and packages to extend what they do.
</p>
</div>
<button onClick={() => setShowCreate(true)} style={primaryButton}>+ New agent</button>
@@ -256,7 +256,7 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
>
<div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>No agents yet</div>
<p style={{ color: 'var(--text-secondary)', fontSize: 13, marginBottom: 20 }}>
- Spin up a managed Hermes agent and connect it to Telegram. Add gbrain to give it long-term memory.
+ Spin up a managed OpenClaw agent and connect it to Telegram. Add gbrain to give it long-term memory.
</p>
<button onClick={onCreate} style={primaryButton}>Create your first agent</button>
</div>
@@ -274,7 +274,7 @@ function CreateAgentModal({
}) {
const [id, setId] = useState('')
const [displayName, setDisplayName] = useState('')
- const [core, setCore] = useState<'openclaw' | 'hermes'>('openclaw')
+ const [core, setCore] = useState<'openclaw'>('openclaw')
const [submitting, setSubmitting] = useState(false)
async function submit(e: React.FormEvent) {
@@ -314,10 +314,10 @@ function CreateAgentModal({
<Field label="Display name (optional)">
<input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder={id || 'My Bot'} style={input} />
</Field>
- <Field label="Core" hint="OpenClaw is the recommended runtime; Hermes is the legacy chat agent.">
- <select value={core} onChange={(e) => setCore(e.target.value as 'openclaw' | 'hermes')} style={input}>
+ <Field label="Core" hint="OpenClaw is the only runtime available right now. Hermes support is coming soon.">
+ <select value={core} onChange={(e) => setCore(e.target.value as 'openclaw')} style={input}>
<option value="openclaw">openclaw</option>
- <option value="hermes">hermes</option>
+ <option value="hermes" disabled>hermes (coming soon)</option>
</select>
</Field>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>