@astroanywhere/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Astro Anywhere
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # @astroanywhere/cli
2
+
3
+ CLI for managing [Astro](https://github.com/astro-anywhere) projects, plans, tasks, and environments.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @astroanywhere/cli
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```bash
14
+ # Configure server connection
15
+ astro-cli config set server-url http://localhost:3001
16
+
17
+ # Authenticate (for remote servers)
18
+ astro-cli login
19
+
20
+ # List projects
21
+ astro-cli project list
22
+
23
+ # View plan
24
+ astro-cli plan tree --project-id <id>
25
+
26
+ # Dispatch a task
27
+ astro-cli task dispatch <nodeId> --project-id <id>
28
+
29
+ # Watch task output
30
+ astro-cli task watch <executionId>
31
+ ```
32
+
33
+ ## Commands
34
+
35
+ | Command | Description |
36
+ |---------|-------------|
37
+ | `project list\|show\|create\|delete` | Manage projects |
38
+ | `plan tree\|create-node\|update-node` | Manage plan graphs |
39
+ | `task list\|show\|dispatch\|cancel\|steer\|watch` | Manage tasks |
40
+ | `env list\|show\|revoke` | Manage environments and machines |
41
+ | `search <query>` | Search across projects, tasks, executions |
42
+ | `activity` | View activity feed |
43
+ | `trace` | View execution traces |
44
+ | `config` | Manage CLI configuration |
45
+ | `login\|logout\|whoami` | Authentication |
46
+
47
+ ## Configuration
48
+
49
+ Config is stored at `~/.astro/config.json`.
50
+
51
+ | Setting | Env var | Description |
52
+ |---------|---------|-------------|
53
+ | `serverUrl` | `ASTRO_SERVER_URL` | Astro server URL |
54
+ | `authToken` | — | Access token (set via `login`) |
55
+
56
+ ## License
57
+
58
+ MIT
@@ -0,0 +1,351 @@
1
+ // src/config.ts
2
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
+ var CONFIG_DIR = join(homedir(), ".astro");
6
+ var CONFIG_FILE = join(CONFIG_DIR, "config.json");
7
+ var DEFAULT_SERVER_URL = "https://api.astroanywhere.com";
8
+ function loadConfig() {
9
+ try {
10
+ if (existsSync(CONFIG_FILE)) {
11
+ const raw = readFileSync(CONFIG_FILE, "utf-8");
12
+ return { serverUrl: DEFAULT_SERVER_URL, ...JSON.parse(raw) };
13
+ }
14
+ } catch {
15
+ }
16
+ return { serverUrl: DEFAULT_SERVER_URL };
17
+ }
18
+ function saveConfig(updates) {
19
+ mkdirSync(CONFIG_DIR, { recursive: true });
20
+ const current = loadConfig();
21
+ const merged = { ...current, ...updates };
22
+ writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2) + "\n");
23
+ }
24
+ function clearAuth() {
25
+ const current = loadConfig();
26
+ delete current.authToken;
27
+ delete current.refreshToken;
28
+ mkdirSync(CONFIG_DIR, { recursive: true });
29
+ writeFileSync(CONFIG_FILE, JSON.stringify(current, null, 2) + "\n");
30
+ }
31
+ function resetConfig() {
32
+ mkdirSync(CONFIG_DIR, { recursive: true });
33
+ writeFileSync(CONFIG_FILE, JSON.stringify({ serverUrl: DEFAULT_SERVER_URL }, null, 2) + "\n");
34
+ }
35
+ function getServerUrl(cliOverride) {
36
+ if (cliOverride) return cliOverride;
37
+ if (process.env.ASTRO_SERVER_URL) return process.env.ASTRO_SERVER_URL;
38
+ const config = loadConfig();
39
+ return config.serverUrl;
40
+ }
41
+
42
+ // src/client.ts
43
+ var AstroClient = class {
44
+ baseUrl;
45
+ headers;
46
+ constructor(opts) {
47
+ this.baseUrl = getServerUrl(opts?.serverUrl);
48
+ const config = loadConfig();
49
+ this.headers = {
50
+ "Content-Type": "application/json",
51
+ ...config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}
52
+ };
53
+ }
54
+ async refreshAccessToken() {
55
+ const config = loadConfig();
56
+ if (!config.refreshToken) return false;
57
+ try {
58
+ const url = new URL("/api/device/refresh", this.baseUrl);
59
+ const res = await fetch(url.toString(), {
60
+ method: "POST",
61
+ headers: { "Content-Type": "application/json" },
62
+ body: JSON.stringify({ refreshToken: config.refreshToken, grantType: "refresh_token" })
63
+ });
64
+ if (!res.ok) return false;
65
+ const data = await res.json();
66
+ saveConfig({
67
+ authToken: data.accessToken,
68
+ ...data.refreshToken ? { refreshToken: data.refreshToken } : {}
69
+ });
70
+ this.headers["Authorization"] = `Bearer ${data.accessToken}`;
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+ async request(method, path, body, params) {
77
+ const url = new URL(path, this.baseUrl);
78
+ if (params) {
79
+ for (const [k, v] of Object.entries(params)) {
80
+ if (v !== void 0) url.searchParams.set(k, v);
81
+ }
82
+ }
83
+ let res = await fetch(url.toString(), {
84
+ method,
85
+ headers: this.headers,
86
+ body: body ? JSON.stringify(body) : void 0
87
+ });
88
+ if (res.status === 401) {
89
+ const refreshed = await this.refreshAccessToken();
90
+ if (refreshed) {
91
+ res = await fetch(url.toString(), {
92
+ method,
93
+ headers: this.headers,
94
+ body: body ? JSON.stringify(body) : void 0
95
+ });
96
+ }
97
+ }
98
+ if (!res.ok) {
99
+ const text = await res.text();
100
+ throw new Error(`API error ${res.status}: ${text}`);
101
+ }
102
+ return res.json();
103
+ }
104
+ get(path, params) {
105
+ return this.request("GET", path, void 0, params);
106
+ }
107
+ post(path, body) {
108
+ return this.request("POST", path, body);
109
+ }
110
+ del(path) {
111
+ return this.request("DELETE", path);
112
+ }
113
+ // ── Projects ────────────────────────────────────────────────────────
114
+ async listProjects() {
115
+ return this.get("/api/data/projects");
116
+ }
117
+ async getProject(id) {
118
+ return this.get(`/api/data/projects/${id}`);
119
+ }
120
+ async createProject(data) {
121
+ return this.post("/api/data/projects", data);
122
+ }
123
+ async deleteProject(id) {
124
+ return this.del(`/api/data/projects/${id}`);
125
+ }
126
+ /**
127
+ * Resolve a partial project ID to a full project.
128
+ * Lists all projects and finds the one matching the prefix.
129
+ * Throws if 0 or >1 matches.
130
+ */
131
+ async resolveProject(partialId) {
132
+ const projects = await this.listProjects();
133
+ const matches = projects.filter((p) => p.id.startsWith(partialId));
134
+ if (matches.length === 0) throw new Error(`No project found matching "${partialId}"`);
135
+ if (matches.length > 1) throw new Error(`Ambiguous ID "${partialId}" matches ${matches.length} projects`);
136
+ return matches[0];
137
+ }
138
+ // ── Plan ────────────────────────────────────────────────────────────
139
+ async getPlan(projectId) {
140
+ const result = await this.get(`/api/data/plan/${projectId}`);
141
+ return {
142
+ nodes: result.nodes ?? [],
143
+ edges: result.edges ?? []
144
+ };
145
+ }
146
+ async getFullPlan() {
147
+ const result = await this.get("/api/data/plan");
148
+ return {
149
+ nodes: result.nodes ?? [],
150
+ edges: result.edges ?? []
151
+ };
152
+ }
153
+ // ── Executions ──────────────────────────────────────────────────────
154
+ /**
155
+ * Get executions map keyed by nodeClientId.
156
+ * Server returns Record<nodeClientId, Execution>.
157
+ */
158
+ async getExecutions() {
159
+ return this.get("/api/data/executions");
160
+ }
161
+ // ── Tool Traces & File Changes ─────────────────────────────────────
162
+ async listToolTraces(executionId) {
163
+ return this.get("/api/data/tool-traces", { executionId });
164
+ }
165
+ async listFileChanges(executionId) {
166
+ return this.get("/api/data/file-changes", { executionId });
167
+ }
168
+ // ── Activity ────────────────────────────────────────────────────────
169
+ async listActivities(params) {
170
+ return this.get("/api/data/activities", params);
171
+ }
172
+ // ── Machines ────────────────────────────────────────────────────────
173
+ async listMachines() {
174
+ const result = await this.get("/api/device/machines");
175
+ return result.machines ?? [];
176
+ }
177
+ async getMachine(id) {
178
+ return this.get(`/api/device/machines/${id}`);
179
+ }
180
+ async revokeMachine(id) {
181
+ return this.del(`/api/device/machines/${id}`);
182
+ }
183
+ /**
184
+ * Resolve a partial machine ID to a full machine.
185
+ * Lists all machines and finds the one matching the prefix.
186
+ */
187
+ async resolveMachine(partialId) {
188
+ const machines = await this.listMachines();
189
+ const matches = machines.filter((m) => !m.isRevoked && m.id.startsWith(partialId));
190
+ if (matches.length === 0) throw new Error(`No active machine found matching "${partialId}"`);
191
+ if (matches.length > 1) throw new Error(`Ambiguous ID "${partialId}" matches ${matches.length} machines`);
192
+ return matches[0];
193
+ }
194
+ // ── Observations ────────────────────────────────────────────────────
195
+ async listObservations(executionId) {
196
+ return this.get("/api/observations", { executionId });
197
+ }
198
+ async getObservationStats(executionId) {
199
+ return this.get("/api/observations/stats", { executionId });
200
+ }
201
+ // ── Search ──────────────────────────────────────────────────────────
202
+ async search(query) {
203
+ return this.get("/api/data/search", { q: query });
204
+ }
205
+ // ── Plan CRUD ─────────────────────────────────────────────────────
206
+ async createPlanNode(data) {
207
+ return this.post("/api/data/plan/nodes", {
208
+ type: "task",
209
+ status: "planned",
210
+ ...data
211
+ });
212
+ }
213
+ async updatePlanNode(nodeId, patch) {
214
+ return this.request("PATCH", `/api/data/plan/nodes/${nodeId}`, patch);
215
+ }
216
+ async deletePlanNode(nodeId) {
217
+ return this.del(`/api/data/plan/nodes/${nodeId}`);
218
+ }
219
+ // ── Project Update ────────────────────────────────────────────────
220
+ async updateProject(id, patch) {
221
+ return this.request("PATCH", `/api/data/projects/${id}`, patch);
222
+ }
223
+ // ── Cancel / Steer ────────────────────────────────────────────────
224
+ async cancelTask(params) {
225
+ return this.post("/api/dispatch/cancel", params);
226
+ }
227
+ async steerTask(params) {
228
+ return this.post("/api/dispatch/steer", params);
229
+ }
230
+ // ── Relay / Environment ───────────────────────────────────────────
231
+ async getRelayStatus() {
232
+ return this.get("/api/relay/status");
233
+ }
234
+ async getProviders() {
235
+ return this.get("/api/health/providers");
236
+ }
237
+ async getSlurmClusters() {
238
+ return this.get("/api/relay/slurm/clusters");
239
+ }
240
+ // ── Observations (extended) ───────────────────────────────────────
241
+ async getTraceSummary(executionId) {
242
+ const url = new URL(`/api/observations/${executionId}/summary`, this.baseUrl);
243
+ const res = await fetch(url.toString(), { headers: this.headers });
244
+ if (!res.ok) {
245
+ const text = await res.text();
246
+ throw new Error(`API error ${res.status}: ${text}`);
247
+ }
248
+ return res.text();
249
+ }
250
+ async listObservationsFiltered(params) {
251
+ return this.get("/api/observations", params);
252
+ }
253
+ // ── SSE Events Stream ─────────────────────────────────────────────
254
+ async streamEvents(params) {
255
+ const url = new URL("/api/events/stream", this.baseUrl);
256
+ if (params?.projectId) url.searchParams.set("projectId", params.projectId);
257
+ const res = await fetch(url.toString(), {
258
+ headers: {
259
+ ...this.headers,
260
+ Accept: "text/event-stream"
261
+ }
262
+ });
263
+ if (!res.ok) {
264
+ const text = await res.text();
265
+ throw new Error(`SSE connect failed (${res.status}): ${text}`);
266
+ }
267
+ return res;
268
+ }
269
+ // ── Dispatch (SSE streaming) ────────────────────────────────────────
270
+ /**
271
+ * Dispatch a task for execution. Returns the raw Response for SSE streaming.
272
+ */
273
+ async dispatchTask(payload) {
274
+ const url = new URL("/api/dispatch/task", this.baseUrl);
275
+ const res = await fetch(url.toString(), {
276
+ method: "POST",
277
+ headers: this.headers,
278
+ body: JSON.stringify(payload)
279
+ });
280
+ if (!res.ok) {
281
+ const text = await res.text();
282
+ throw new Error(`Dispatch failed (${res.status}): ${text}`);
283
+ }
284
+ return res;
285
+ }
286
+ };
287
+ async function streamDispatchToStdout(response) {
288
+ if (!response.body) {
289
+ console.log("Task dispatched (no stream)");
290
+ return;
291
+ }
292
+ const reader = response.body.getReader();
293
+ const decoder = new TextDecoder();
294
+ let buffer = "";
295
+ while (true) {
296
+ const { done, value } = await reader.read();
297
+ if (done) break;
298
+ buffer += decoder.decode(value, { stream: true });
299
+ const lines = buffer.split("\n");
300
+ buffer = lines.pop() ?? "";
301
+ for (const line of lines) {
302
+ if (line.startsWith("data: ")) {
303
+ try {
304
+ const event = JSON.parse(line.slice(6));
305
+ switch (event.type) {
306
+ case "text":
307
+ process.stdout.write(event.content ?? "");
308
+ break;
309
+ case "tool_use":
310
+ console.log(`
311
+ [tool] ${event.name}`);
312
+ break;
313
+ case "result":
314
+ console.log(`
315
+ --- Result: ${event.status} ---`);
316
+ if (event.summary) console.log(event.summary);
317
+ break;
318
+ case "error":
319
+ console.error(`
320
+ Error: ${event.message}`);
321
+ break;
322
+ case "done":
323
+ break;
324
+ }
325
+ } catch {
326
+ }
327
+ }
328
+ }
329
+ }
330
+ }
331
+ var _client = null;
332
+ var _clientUrl;
333
+ function getClient(serverUrl) {
334
+ const resolvedUrl = getServerUrl(serverUrl);
335
+ if (!_client || resolvedUrl !== _clientUrl) {
336
+ _client = new AstroClient({ serverUrl });
337
+ _clientUrl = resolvedUrl;
338
+ }
339
+ return _client;
340
+ }
341
+
342
+ export {
343
+ loadConfig,
344
+ saveConfig,
345
+ clearAuth,
346
+ resetConfig,
347
+ getServerUrl,
348
+ AstroClient,
349
+ streamDispatchToStdout,
350
+ getClient
351
+ };
package/dist/client.js ADDED
@@ -0,0 +1,10 @@
1
+ import {
2
+ AstroClient,
3
+ getClient,
4
+ streamDispatchToStdout
5
+ } from "./chunk-PYFBZGQG.js";
6
+ export {
7
+ AstroClient,
8
+ getClient,
9
+ streamDispatchToStdout
10
+ };