@celestoai/sdk 0.1.3 → 0.1.4

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/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -24,7 +34,10 @@ __export(src_exports, {
24
34
  CelestoError: () => CelestoError,
25
35
  CelestoNetworkError: () => CelestoNetworkError,
26
36
  Computer: () => Computer,
27
- GatekeeperClient: () => GatekeeperClient
37
+ GatekeeperClient: () => GatekeeperClient,
38
+ MISSING_CREDENTIALS_MESSAGE: () => MISSING_CREDENTIALS_MESSAGE,
39
+ resolveCelestoApiKey: () => resolveCelestoApiKey,
40
+ resolveClientConfig: () => resolveClientConfig
28
41
  });
29
42
  module.exports = __toCommonJS(src_exports);
30
43
 
@@ -65,9 +78,9 @@ var CelestoNetworkError = class extends CelestoError {
65
78
  };
66
79
 
67
80
  // src/core/http.ts
68
- var joinUrl = (baseUrl, path) => {
81
+ var joinUrl = (baseUrl, path2) => {
69
82
  const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
70
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
83
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
71
84
  return `${trimmedBase}${normalizedPath}`;
72
85
  };
73
86
  var buildQuery = (query) => {
@@ -115,7 +128,7 @@ var extractErrorMessage = (data, status) => {
115
128
  }
116
129
  return `Request failed with status ${status}`;
117
130
  };
118
- var request = async (ctx, options) => {
131
+ var buildRequestInit = (ctx, options) => {
119
132
  const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
120
133
  const headers = {
121
134
  ...ctx.headers ?? {},
@@ -133,13 +146,16 @@ var request = async (ctx, options) => {
133
146
  const init = {
134
147
  method: options.method,
135
148
  headers,
136
- body: void 0,
137
149
  signal: options.signal
138
150
  };
139
151
  if (options.body !== void 0) {
140
152
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
141
153
  init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
142
154
  }
155
+ return { url, init };
156
+ };
157
+ var request = async (ctx, options) => {
158
+ const { url, init } = buildRequestInit(ctx, options);
143
159
  let timeoutId;
144
160
  let controller;
145
161
  if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
@@ -167,6 +183,29 @@ var request = async (ctx, options) => {
167
183
  }
168
184
  }
169
185
  };
186
+ var requestStream = async (ctx, options) => {
187
+ const { url, init } = buildRequestInit(ctx, options);
188
+ try {
189
+ const response = await ctx.fetch(url, init);
190
+ if (!response.ok) {
191
+ const data = await parseResponseBody(response);
192
+ const message = extractErrorMessage(data, response.status);
193
+ throw new CelestoApiError(
194
+ message,
195
+ response.status,
196
+ data,
197
+ response.headers.get("x-request-id") ?? void 0
198
+ );
199
+ }
200
+ return response;
201
+ } catch (err) {
202
+ if (err instanceof CelestoApiError) {
203
+ throw err;
204
+ }
205
+ const error = err instanceof Error ? err : new Error(String(err));
206
+ throw new CelestoNetworkError(error.message, error);
207
+ }
208
+ };
170
209
 
171
210
  // src/gatekeeper/client.ts
172
211
  var toConnectRequest = (payload) => ({
@@ -219,7 +258,7 @@ var toDriveFile = (payload) => ({
219
258
  shared: payload.shared ?? null,
220
259
  ownedByMe: payload.owned_by_me ?? null
221
260
  });
222
- var gatekeeperPath = (path) => `/v1/gatekeeper${path}`;
261
+ var gatekeeperPath = (path2) => `/v1/gatekeeper${path2}`;
223
262
  var pickOverrides = (options) => ({
224
263
  headers: options?.headers,
225
264
  signal: options?.signal
@@ -336,6 +375,56 @@ var GatekeeperClient = class {
336
375
  }
337
376
  };
338
377
 
378
+ // src/core/auth.ts
379
+ var import_node_child_process = require("child_process");
380
+ var import_promises = require("fs/promises");
381
+ var import_node_path = __toESM(require("path"), 1);
382
+ var import_node_util = require("util");
383
+ var import_dotenv = require("dotenv");
384
+ var execFile = (0, import_node_util.promisify)(import_node_child_process.execFile);
385
+ var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
386
+ function nonEmpty(value) {
387
+ const trimmed = value?.trim();
388
+ return trimmed ? trimmed : void 0;
389
+ }
390
+ async function readDotEnvApiKey(cwd, readDotEnv) {
391
+ try {
392
+ const contents = await readDotEnv(import_node_path.default.join(cwd, ".env"));
393
+ return nonEmpty((0, import_dotenv.parse)(contents).CELESTO_API_KEY);
394
+ } catch {
395
+ return void 0;
396
+ }
397
+ }
398
+ async function loadCliApiKey() {
399
+ try {
400
+ const { stdout } = await execFile("celesto", ["auth", "token"], {
401
+ encoding: "utf8",
402
+ timeout: 5e3,
403
+ maxBuffer: 64 * 1024
404
+ });
405
+ return nonEmpty(stdout);
406
+ } catch {
407
+ return void 0;
408
+ }
409
+ }
410
+ async function resolveCelestoApiKey(options = {}) {
411
+ const env = options.env ?? process.env;
412
+ const environmentKey = nonEmpty(env.CELESTO_API_KEY);
413
+ if (environmentKey) return environmentKey;
414
+ const dotEnvKey = await readDotEnvApiKey(
415
+ options.cwd ?? process.cwd(),
416
+ options.readDotEnv ?? ((filePath) => (0, import_promises.readFile)(filePath, "utf8"))
417
+ );
418
+ if (dotEnvKey) return dotEnvKey;
419
+ return (options.loadSavedApiKey ?? loadCliApiKey)();
420
+ }
421
+ async function resolveClientConfig(config = {}, options = {}) {
422
+ if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
423
+ const apiKey = await resolveCelestoApiKey(options);
424
+ if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
425
+ return { ...config, token: apiKey };
426
+ }
427
+
339
428
  // src/computers/client.ts
340
429
  var toConnection2 = (payload) => {
341
430
  if (!payload) {
@@ -374,11 +463,42 @@ var toComputerInfo = (payload) => ({
374
463
  createdAt: payload.created_at,
375
464
  stoppedAt: payload.stopped_at ?? null
376
465
  });
377
- var toExecResponse = (payload) => ({
466
+ var toExecResponse = (payload) => {
467
+ const response = {
468
+ exitCode: payload.exit_code,
469
+ stdout: payload.stdout,
470
+ stderr: payload.stderr
471
+ };
472
+ if (payload.command_id !== void 0) response.commandId = payload.command_id;
473
+ if (payload.duration_ms !== void 0) response.durationMs = payload.duration_ms;
474
+ if (payload.timed_out !== void 0) response.timedOut = payload.timed_out;
475
+ return response;
476
+ };
477
+ var toCommandHistoryEntry = (payload) => ({
478
+ commandId: payload.command_id,
479
+ source: payload.source,
480
+ status: payload.status,
481
+ startedAt: payload.started_at,
482
+ endedAt: payload.ended_at,
483
+ durationMs: payload.duration_ms,
484
+ timeoutSeconds: payload.timeout_seconds,
378
485
  exitCode: payload.exit_code,
379
- stdout: payload.stdout,
380
- stderr: payload.stderr
486
+ stdoutBytes: payload.stdout_bytes,
487
+ stderrBytes: payload.stderr_bytes,
488
+ errorType: payload.error_type
381
489
  });
490
+ var toTerminalConnectionInfo = (payload) => {
491
+ const separator = payload.gateway_url.includes("?") ? "&" : "?";
492
+ return {
493
+ terminalId: payload.terminal_id,
494
+ gatewayUrl: payload.gateway_url,
495
+ url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
496
+ token: payload.token,
497
+ expiresAt: payload.expires_at,
498
+ headers: {},
499
+ firstMessage: ""
500
+ };
501
+ };
382
502
  var toSandboxTemplateInfo = (payload) => ({
383
503
  id: payload.id,
384
504
  displayName: payload.display_name,
@@ -498,11 +618,104 @@ var buildCreateComputerBody = (params) => {
498
618
  }
499
619
  return body;
500
620
  };
501
- var computersPath = (path) => `/v1/computers${path}`;
621
+ var computersPath = (path2) => `/v1/computers${path2}`;
502
622
  var pickOverrides2 = (options) => ({
503
623
  headers: options?.headers,
504
624
  signal: options?.signal
505
625
  });
626
+ var optionalNumber = (value) => typeof value === "number" ? value : void 0;
627
+ var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
628
+ var parseExecStreamEvent = (value) => {
629
+ if (!value || typeof value !== "object") {
630
+ throw new Error("Celesto returned an invalid command stream event.");
631
+ }
632
+ const event = value;
633
+ if (event.type === "stdout" || event.type === "stderr") {
634
+ if (typeof event.data !== "string") {
635
+ throw new Error("Celesto returned command output without text data.");
636
+ }
637
+ return { type: event.type, data: event.data };
638
+ }
639
+ if (event.type === "started") {
640
+ if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
641
+ throw new Error("Celesto returned an invalid command-start event.");
642
+ }
643
+ return {
644
+ type: "started",
645
+ commandId: event.command_id,
646
+ startedAtUnixMs: event.started_at_unix_ms,
647
+ timeoutSeconds: event.timeout_seconds
648
+ };
649
+ }
650
+ if (event.type === "exit") {
651
+ if (typeof event.exit_code !== "number") {
652
+ throw new Error("Celesto returned an invalid command-exit event.");
653
+ }
654
+ const result = {
655
+ type: "exit",
656
+ exitCode: event.exit_code
657
+ };
658
+ if (typeof event.command_id === "string") result.commandId = event.command_id;
659
+ const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
660
+ const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
661
+ const durationMs = optionalNumber(event.duration_ms);
662
+ const timedOut = optionalBoolean(event.timed_out);
663
+ if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
664
+ if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
665
+ if (durationMs !== void 0) result.durationMs = durationMs;
666
+ if (timedOut !== void 0) result.timedOut = timedOut;
667
+ return result;
668
+ }
669
+ throw new Error("Celesto returned an unknown command stream event.");
670
+ };
671
+ var parseSseDataLine = (line) => {
672
+ const text = line.trim();
673
+ if (!text || !text.startsWith("data:")) {
674
+ return void 0;
675
+ }
676
+ const data = text.slice("data:".length).trim();
677
+ if (!data || data === "[DONE]") {
678
+ return void 0;
679
+ }
680
+ try {
681
+ return parseExecStreamEvent(JSON.parse(data));
682
+ } catch (error) {
683
+ if (error instanceof SyntaxError) {
684
+ throw new Error("Celesto returned malformed JSON in the command stream.");
685
+ }
686
+ throw error;
687
+ }
688
+ };
689
+ var createManagedSignal = (signal, timeoutMs) => {
690
+ if (!timeoutMs || timeoutMs <= 0) {
691
+ return { signal, cleanup: () => {
692
+ } };
693
+ }
694
+ const controller = new AbortController();
695
+ const abort = () => controller.abort();
696
+ if (signal?.aborted) {
697
+ abort();
698
+ } else {
699
+ signal?.addEventListener("abort", abort, { once: true });
700
+ }
701
+ const timer = setTimeout(abort, timeoutMs);
702
+ return {
703
+ signal: controller.signal,
704
+ cleanup: () => {
705
+ clearTimeout(timer);
706
+ signal?.removeEventListener("abort", abort);
707
+ }
708
+ };
709
+ };
710
+ var toNetworkError = (error) => {
711
+ if (error instanceof CelestoNetworkError) return error;
712
+ const cause = error instanceof Error ? error : new Error(String(error));
713
+ return new CelestoNetworkError(cause.message, cause);
714
+ };
715
+ var withFallbackCommandId = (event, commandId) => {
716
+ if (event.type !== "exit" || event.commandId || !commandId) return event;
717
+ return { ...event, commandId };
718
+ };
506
719
  var ComputersClient = class {
507
720
  constructor(config) {
508
721
  this.config = config;
@@ -554,17 +767,113 @@ var ComputersClient = class {
554
767
  return toComputerInfo(data);
555
768
  }
556
769
  async exec(computerId, command, params = {}, options) {
770
+ const ctx = buildRequestContext(this.config);
771
+ const managedSignal = createManagedSignal(
772
+ params.signal ?? options?.signal,
773
+ this.config.timeoutMs
774
+ );
775
+ try {
776
+ const data = await request(ctx, {
777
+ method: "POST",
778
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
779
+ body: {
780
+ command,
781
+ timeout: params.timeout ?? 30
782
+ },
783
+ headers: options?.headers,
784
+ signal: managedSignal.signal
785
+ });
786
+ return toExecResponse(data);
787
+ } finally {
788
+ managedSignal.cleanup();
789
+ }
790
+ }
791
+ async *execStream(computerId, command, params = {}, options) {
792
+ const ctx = buildRequestContext(this.config);
793
+ const managedSignal = createManagedSignal(
794
+ params.signal ?? options?.signal,
795
+ this.config.timeoutMs
796
+ );
797
+ let reader;
798
+ let completed = false;
799
+ try {
800
+ const response = await requestStream(ctx, {
801
+ method: "POST",
802
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
803
+ body: {
804
+ command,
805
+ timeout: params.timeout ?? 30
806
+ },
807
+ headers: options?.headers,
808
+ signal: managedSignal.signal
809
+ });
810
+ if (!response.body) {
811
+ throw new Error("Celesto did not return a command output stream.");
812
+ }
813
+ const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
814
+ reader = response.body.getReader();
815
+ const decoder = new TextDecoder();
816
+ let buffer = "";
817
+ while (true) {
818
+ let chunk;
819
+ try {
820
+ chunk = await reader.read();
821
+ } catch (error) {
822
+ throw toNetworkError(error);
823
+ }
824
+ if (chunk.done) {
825
+ completed = true;
826
+ buffer += decoder.decode();
827
+ break;
828
+ }
829
+ buffer += decoder.decode(chunk.value, { stream: true });
830
+ let newlineIndex = buffer.indexOf("\n");
831
+ while (newlineIndex !== -1) {
832
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
833
+ buffer = buffer.slice(newlineIndex + 1);
834
+ const parsed = parseSseDataLine(line);
835
+ if (parsed) {
836
+ const event = withFallbackCommandId(parsed, responseCommandId);
837
+ yield event;
838
+ if (event.type === "exit") return;
839
+ }
840
+ newlineIndex = buffer.indexOf("\n");
841
+ }
842
+ }
843
+ if (buffer) {
844
+ const parsed = parseSseDataLine(buffer);
845
+ if (parsed) {
846
+ const event = withFallbackCommandId(parsed, responseCommandId);
847
+ yield event;
848
+ if (event.type === "exit") return;
849
+ }
850
+ }
851
+ throw new Error("Command stream ended before Celesto returned an exit status.");
852
+ } finally {
853
+ if (reader) {
854
+ if (!completed) {
855
+ try {
856
+ await reader.cancel();
857
+ } catch {
858
+ }
859
+ }
860
+ reader.releaseLock();
861
+ }
862
+ managedSignal.cleanup();
863
+ }
864
+ }
865
+ async listCommandHistory(computerId, params = {}, options) {
557
866
  const ctx = buildRequestContext(this.config);
558
867
  const data = await request(ctx, {
559
- method: "POST",
560
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
561
- body: {
562
- command,
563
- timeout: params.timeout ?? 30
564
- },
868
+ method: "GET",
869
+ path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
870
+ query: { limit: params.limit },
565
871
  ...pickOverrides2(options)
566
872
  });
567
- return toExecResponse(data);
873
+ return {
874
+ commands: data.commands.map(toCommandHistoryEntry),
875
+ count: data.count
876
+ };
568
877
  }
569
878
  async stop(computerId, options) {
570
879
  const ctx = buildRequestContext(this.config);
@@ -621,43 +930,19 @@ var ComputersClient = class {
621
930
  });
622
931
  return toPublishedPortInfo(data);
623
932
  }
624
- /**
625
- * Get connection info for opening a WebSocket terminal session.
626
- *
627
- * Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
628
- * The name is resolved to the canonical ID via a GET call — the backend's
629
- * WebSocket endpoint does not resolve names on its own.
630
- *
631
- * Returns the URL, headers, and first message needed to open the connection
632
- * with any WebSocket library of your choice.
633
- *
634
- * @example
635
- * ```ts
636
- * const conn = await client.getTerminalConnection("my-computer");
637
- * const ws = new WebSocket(conn.url, { headers: conn.headers });
638
- * ws.on("open", () => ws.send(conn.firstMessage));
639
- * ws.on("message", (data) => process.stdout.write(data));
640
- * ```
641
- */
642
- async getTerminalConnection(computerIdOrName) {
643
- const info = await this.get(computerIdOrName);
933
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
934
+ async createTerminalSession(computerIdOrName, options) {
644
935
  const ctx = buildRequestContext(this.config);
645
- if (!ctx.token) {
646
- throw new Error("A token is required for terminal connections");
647
- }
648
- const wsBase = ctx.baseUrl.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
649
- const url = `${wsBase}/v1/computers/${encodeURIComponent(info.id)}/terminal`;
650
- const headers = {
651
- Authorization: `Bearer ${ctx.token}`
652
- };
653
- if (ctx.organizationId) {
654
- headers["X-Current-Organization"] = ctx.organizationId;
655
- }
656
- return {
657
- url,
658
- headers,
659
- firstMessage: JSON.stringify({ token: ctx.token })
660
- };
936
+ const data = await request(ctx, {
937
+ method: "POST",
938
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
939
+ ...pickOverrides2(options)
940
+ });
941
+ return toTerminalConnectionInfo(data);
942
+ }
943
+ /** @deprecated Use createTerminalSession(). */
944
+ async getTerminalConnection(computerIdOrName, options) {
945
+ return this.createTerminalSession(computerIdOrName, options);
661
946
  }
662
947
  };
663
948
 
@@ -671,26 +956,26 @@ var Computer = class _Computer {
671
956
  this.info = info;
672
957
  }
673
958
  /** Create a new computer and return an object with methods on it. */
674
- static async create(params = {}, config = defaultConfig()) {
675
- const client = new ComputersClient(config);
959
+ static async create(params = {}, config) {
960
+ const client = new ComputersClient(await resolveClientConfig(config));
676
961
  const info = await client.create(params);
677
962
  return new _Computer(client, info);
678
963
  }
679
964
  /** Load an existing computer by name or ID. */
680
- static async get(computerIdOrName, config = defaultConfig()) {
681
- const client = new ComputersClient(config);
965
+ static async get(computerIdOrName, config) {
966
+ const client = new ComputersClient(await resolveClientConfig(config));
682
967
  const info = await client.get(computerIdOrName);
683
968
  return new _Computer(client, info);
684
969
  }
685
970
  /** List computers in the current account. */
686
- static async list(params = {}, config = defaultConfig()) {
687
- const client = new ComputersClient(config);
971
+ static async list(params = {}, config) {
972
+ const client = new ComputersClient(await resolveClientConfig(config));
688
973
  const response = await client.list(params);
689
974
  return response.computers.map((info) => new _Computer(client, info));
690
975
  }
691
976
  /** List available computer templates. */
692
- static async listTemplates(config = defaultConfig()) {
693
- const client = new ComputersClient(config);
977
+ static async listTemplates(config) {
978
+ const client = new ComputersClient(await resolveClientConfig(config));
694
979
  return client.listTemplates();
695
980
  }
696
981
  /** Wrap an existing API response in the convenience object. */
@@ -760,6 +1045,26 @@ var Computer = class _Computer {
760
1045
  async exec(command, params = {}) {
761
1046
  return this.run(command, params);
762
1047
  }
1048
+ /** Run a shell command and stream output and exit events as they arrive. */
1049
+ runStream(command, params = {}) {
1050
+ return this.client.execStream(this.id, command, params);
1051
+ }
1052
+ /** Alias for runStream(). */
1053
+ execStream(command, params = {}) {
1054
+ return this.runStream(command, params);
1055
+ }
1056
+ /** List recent commands executed on this computer. */
1057
+ async listCommandHistory(params = {}) {
1058
+ return this.client.listCommandHistory(this.id, params);
1059
+ }
1060
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
1061
+ async createTerminalSession() {
1062
+ return this.client.createTerminalSession(this.id);
1063
+ }
1064
+ /** @deprecated Use createTerminalSession(). */
1065
+ async getTerminalConnection() {
1066
+ return this.createTerminalSession();
1067
+ }
763
1068
  /** Stop this computer and update the local data. */
764
1069
  async stop() {
765
1070
  this.info = await this.client.stop(this.id);
@@ -807,6 +1112,9 @@ var Computer = class _Computer {
807
1112
  CelestoError,
808
1113
  CelestoNetworkError,
809
1114
  Computer,
810
- GatekeeperClient
1115
+ GatekeeperClient,
1116
+ MISSING_CREDENTIALS_MESSAGE,
1117
+ resolveCelestoApiKey,
1118
+ resolveClientConfig
811
1119
  });
812
1120
  //# sourceMappingURL=index.cjs.map