Repository navigation
Expand file tree
/
Copy pathcommandagi.go
More file actions
204 lines (187 loc) · 6.81 KB
/
Copy pathcommandagi.go
File metadata and controls
204 lines (187 loc) · 6.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Package commandagi is the Go SDK for CommandAGI — launch cloud computers and 3D robot simulations
// and control them programmatically, or bring your own robot online.
//
// Status: the HTTP control surface (launch / attach / snapshot / stop, register-robot) is
// implemented. The realtime stream/control path (observe frames + send actions over the WebSocket)
// is marked TODO below — the protocol is documented inline; wire it with a WebSocket client
// (e.g. github.com/coder/websocket). The Python and Node SDKs are complete references.
//
// cagi := commandagi.New("") // reads COMMANDAGI_API_KEY
// world, _ := cagi.Launch("simulation/warehouse")
// defer world.Close()
// // obs, _ := world.Observe() // TODO (WebSocket)
package commandagi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
const defaultBaseURL = "https://api.commandagi.com"
// Built-in 3D simulation worlds (PyBullet) and computers.
var (
Simulations = []string{"simulation/warehouse", "simulation/house-on-fire", "simulation/school"}
Computers = []string{"computer/software-engineer", "computer/robots-engineer", "computer/video-professional"}
)
// Client talks to the CommandAGI API. Authenticate with an API key (operator scope).
type Client struct {
APIKey string
BaseURL string
HTTP *http.Client
}
// New returns a Client. If apiKey is "", it reads COMMANDAGI_API_KEY; baseURL falls back to
// COMMANDAGI_BASE_URL then the production API.
func New(apiKey string) *Client {
if apiKey == "" {
apiKey = os.Getenv("COMMANDAGI_API_KEY")
}
base := os.Getenv("COMMANDAGI_BASE_URL")
if base == "" {
base = defaultBaseURL
}
return &Client{APIKey: apiKey, BaseURL: strings.TrimRight(base, "/"), HTTP: &http.Client{Timeout: 60 * time.Second}}
}
func (c *Client) do(method, path string, body any) (map[string]any, error) {
var rdr io.Reader
if body != nil {
b, _ := json.Marshal(body)
rdr = bytes.NewReader(b)
}
req, err := http.NewRequest(method, c.BaseURL+path, rdr)
if err != nil {
return nil, err
}
req.Header.Set("authorization", "Bearer "+c.APIKey)
req.Header.Set("content-type", "application/json")
res, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s -> %d: %s", method, path, res.StatusCode, string(raw))
}
out := map[string]any{}
if len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
}
return out, nil
}
// World is a live world you control. Create it with Launch.
type World struct {
SessionID string
DeviceID string
Kind string // "robot" | "computer"
client *Client
// TODO: hold the WebSocket connection + the latest frame here.
}
// Launch provisions a world (e.g. "simulation/warehouse" or "computer/software-engineer") and returns
// it. The world has no agent — you drive it. Always Close it to release the VM.
func (c *Client) Launch(template string) (*World, error) {
isRobot := strings.HasPrefix(template, "simulation/") || strings.HasPrefix(template, "physical/")
m, err := c.do("POST", "/machines", map[string]any{"title": template})
if err != nil {
return nil, err
}
sid, _ := m["sessionId"].(string)
endpoint := "computers"
if isRobot {
endpoint = "robots"
}
r, err := c.do("POST", "/sessions/"+sid+"/"+endpoint, map[string]any{"templateId": template})
if err != nil {
_ = c.StopSession(sid)
return nil, err
}
if r["status"] != "granted" {
_ = c.StopSession(sid)
return nil, fmt.Errorf("launch was not granted: %v", r)
}
dev, _ := r["deviceId"].(string)
kind := "computer"
if isRobot {
kind = "robot"
}
// TODO: poll GET /sessions/{sid} until a device status == "live" (~60–90s), then open the
// realtime WebSocket wss://…/rt/session/{sid}?role=owner and send {"t":"remote.request",...}.
return &World{SessionID: sid, DeviceID: dev, Kind: kind, client: c}, nil
}
// Observe returns the latest sensor frame (JPEG for sims, PNG for computers).
//
// TODO: implement over the realtime WebSocket. Frames arrive as
// {"t":"frame","deviceId":…,"channelId":"cam-head","url":"data:image/jpeg;base64,…"}; decode the
// data URL and return the bytes.
func (w *World) Observe() ([]byte, error) {
return nil, fmt.Errorf("Observe: not implemented yet — see the Python/Node SDKs; wire a WebSocket client")
}
// Act sends a control action, e.g. Act("move", map[string]any{"speed": 0.8}).
//
// TODO: send {"t":"control","deviceId":w.DeviceID,"action":action,"payload":payload} over the WS.
func (w *World) Act(action string, payload map[string]any) error {
return fmt.Errorf("Act: not implemented yet — wire a WebSocket client")
}
// Close stops the world and releases the cloud VM.
func (w *World) Close() error {
return w.client.StopSession(w.SessionID)
}
// StopSession stops a session/machine and releases its devices.
func (c *Client) StopSession(sessionID string) error {
_, err := c.do("POST", "/sessions/"+sessionID+"/stop", nil)
return err
}
// Bridge streams YOUR robot's camera into a session and applies received actions. See RegisterRobot.
type Bridge struct {
ControlURL string
Token string
DeviceID string
SessionID string
SessionURL string
client *Client
}
// RegisterRobot registers your robot as a device and returns a Bridge.
func (c *Client) RegisterRobot(name string) (*Bridge, error) {
if name == "" {
name = "my-robot"
}
m, err := c.do("POST", "/machines", map[string]any{"title": name})
if err != nil {
return nil, err
}
sid, _ := m["sessionId"].(string)
dev, err := c.do("POST", "/sessions/"+sid+"/connect-device", map[string]any{"kind": "robot", "name": name})
if err != nil {
_ = c.StopSession(sid)
return nil, err
}
webURL := strings.Replace(strings.Replace(c.BaseURL, "https://api-dev.", "https://dev.", 1), "https://api.", "https://", 1)
return &Bridge{
ControlURL: str(dev["controlUrl"]),
Token: str(dev["token"]),
DeviceID: str(dev["deviceId"]),
SessionID: sid,
SessionURL: webURL + "/machine/" + sid,
client: c,
}, nil
}
// Run publishes camera frames and applies incoming actions.
//
// TODO: connect a WebSocket to ControlURL + "&runtime=1&role=agent&token="+Token, then:
// - send {"type":"status","status":"live"} and {"type":"channels","channels":[{"channelId":"cam-head",…}]}
// - every 1/fps, send {"type":"frame","channelId":"cam-head","url":"data:image/jpeg;base64,"+b64(camera())}
// - on {"type":"control","action":…,"payload":…}, call onAction(action, payload)
func (b *Bridge) Run(camera func() []byte, onAction func(action string, payload map[string]any), fps int) error {
return fmt.Errorf("Run: not implemented yet — wire a WebSocket client (see Python/Node SDKs)")
}
// Close stops the bridge and releases the session.
func (b *Bridge) Close() error {
return b.client.StopSession(b.SessionID)
}
func str(v any) string {
s, _ := v.(string)
return s
}