@celestoai/sdk 0.1.2 → 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.
@@ -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,26 +17,32 @@ 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/computers/index.ts
21
31
  var computers_exports = {};
22
32
  __export(computers_exports, {
23
- ComputersClient: () => ComputersClient
33
+ Computer: () => Computer,
34
+ MISSING_CREDENTIALS_MESSAGE: () => MISSING_CREDENTIALS_MESSAGE,
35
+ resolveCelestoApiKey: () => resolveCelestoApiKey,
36
+ resolveClientConfig: () => resolveClientConfig
24
37
  });
25
38
  module.exports = __toCommonJS(computers_exports);
26
39
 
27
- // src/core/config.ts
28
- var DEFAULT_BASE_URL = "https://api.celesto.ai";
29
- var buildRequestContext = (config) => ({
30
- fetch: config.fetch ?? fetch,
31
- baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
32
- token: config.token ?? config.apiKey,
33
- organizationId: config.organizationId,
34
- userAgent: config.userAgent,
35
- timeoutMs: config.timeoutMs,
36
- headers: config.headers
37
- });
40
+ // src/core/auth.ts
41
+ var import_node_child_process = require("child_process");
42
+ var import_promises = require("fs/promises");
43
+ var import_node_path = __toESM(require("path"), 1);
44
+ var import_node_util = require("util");
45
+ var import_dotenv = require("dotenv");
38
46
 
39
47
  // src/core/errors.ts
40
48
  var CelestoError = class extends Error {
@@ -60,10 +68,67 @@ var CelestoNetworkError = class extends CelestoError {
60
68
  }
61
69
  };
62
70
 
71
+ // src/core/auth.ts
72
+ var execFile = (0, import_node_util.promisify)(import_node_child_process.execFile);
73
+ var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
74
+ function nonEmpty(value) {
75
+ const trimmed = value?.trim();
76
+ return trimmed ? trimmed : void 0;
77
+ }
78
+ async function readDotEnvApiKey(cwd, readDotEnv) {
79
+ try {
80
+ const contents = await readDotEnv(import_node_path.default.join(cwd, ".env"));
81
+ return nonEmpty((0, import_dotenv.parse)(contents).CELESTO_API_KEY);
82
+ } catch {
83
+ return void 0;
84
+ }
85
+ }
86
+ async function loadCliApiKey() {
87
+ try {
88
+ const { stdout } = await execFile("celesto", ["auth", "token"], {
89
+ encoding: "utf8",
90
+ timeout: 5e3,
91
+ maxBuffer: 64 * 1024
92
+ });
93
+ return nonEmpty(stdout);
94
+ } catch {
95
+ return void 0;
96
+ }
97
+ }
98
+ async function resolveCelestoApiKey(options = {}) {
99
+ const env = options.env ?? process.env;
100
+ const environmentKey = nonEmpty(env.CELESTO_API_KEY);
101
+ if (environmentKey) return environmentKey;
102
+ const dotEnvKey = await readDotEnvApiKey(
103
+ options.cwd ?? process.cwd(),
104
+ options.readDotEnv ?? ((filePath) => (0, import_promises.readFile)(filePath, "utf8"))
105
+ );
106
+ if (dotEnvKey) return dotEnvKey;
107
+ return (options.loadSavedApiKey ?? loadCliApiKey)();
108
+ }
109
+ async function resolveClientConfig(config = {}, options = {}) {
110
+ if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
111
+ const apiKey = await resolveCelestoApiKey(options);
112
+ if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
113
+ return { ...config, token: apiKey };
114
+ }
115
+
116
+ // src/core/config.ts
117
+ var DEFAULT_BASE_URL = "https://api.celesto.ai";
118
+ var buildRequestContext = (config) => ({
119
+ fetch: config.fetch ?? fetch,
120
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
121
+ token: config.token ?? config.apiKey,
122
+ organizationId: config.organizationId,
123
+ userAgent: config.userAgent,
124
+ timeoutMs: config.timeoutMs,
125
+ headers: config.headers
126
+ });
127
+
63
128
  // src/core/http.ts
64
- var joinUrl = (baseUrl, path) => {
129
+ var joinUrl = (baseUrl, path2) => {
65
130
  const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
66
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
131
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
67
132
  return `${trimmedBase}${normalizedPath}`;
68
133
  };
69
134
  var buildQuery = (query) => {
@@ -111,7 +176,7 @@ var extractErrorMessage = (data, status) => {
111
176
  }
112
177
  return `Request failed with status ${status}`;
113
178
  };
114
- var request = async (ctx, options) => {
179
+ var buildRequestInit = (ctx, options) => {
115
180
  const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
116
181
  const headers = {
117
182
  ...ctx.headers ?? {},
@@ -129,13 +194,16 @@ var request = async (ctx, options) => {
129
194
  const init = {
130
195
  method: options.method,
131
196
  headers,
132
- body: void 0,
133
197
  signal: options.signal
134
198
  };
135
199
  if (options.body !== void 0) {
136
200
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
137
201
  init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
138
202
  }
203
+ return { url, init };
204
+ };
205
+ var request = async (ctx, options) => {
206
+ const { url, init } = buildRequestInit(ctx, options);
139
207
  let timeoutId;
140
208
  let controller;
141
209
  if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
@@ -163,6 +231,29 @@ var request = async (ctx, options) => {
163
231
  }
164
232
  }
165
233
  };
234
+ var requestStream = async (ctx, options) => {
235
+ const { url, init } = buildRequestInit(ctx, options);
236
+ try {
237
+ const response = await ctx.fetch(url, init);
238
+ if (!response.ok) {
239
+ const data = await parseResponseBody(response);
240
+ const message = extractErrorMessage(data, response.status);
241
+ throw new CelestoApiError(
242
+ message,
243
+ response.status,
244
+ data,
245
+ response.headers.get("x-request-id") ?? void 0
246
+ );
247
+ }
248
+ return response;
249
+ } catch (err) {
250
+ if (err instanceof CelestoApiError) {
251
+ throw err;
252
+ }
253
+ const error = err instanceof Error ? err : new Error(String(err));
254
+ throw new CelestoNetworkError(error.message, error);
255
+ }
256
+ };
166
257
 
167
258
  // src/computers/client.ts
168
259
  var toConnection = (payload) => {
@@ -178,6 +269,14 @@ var toConnection = (payload) => {
178
269
  }
179
270
  return out;
180
271
  };
272
+ var toPublishedPortInfo = (payload) => ({
273
+ id: payload.id ?? null,
274
+ computerId: payload.computer_id,
275
+ port: payload.port,
276
+ url: payload.url ?? null,
277
+ status: payload.status,
278
+ createdAt: payload.created_at ?? null
279
+ });
181
280
  var toComputerInfo = (payload) => ({
182
281
  id: payload.id,
183
282
  name: payload.name,
@@ -189,15 +288,47 @@ var toComputerInfo = (payload) => ({
189
288
  templateId: payload.template_id,
190
289
  templateVersion: payload.template_version ?? null,
191
290
  connection: toConnection(payload.connection),
291
+ publishedPorts: payload.published_ports?.map(toPublishedPortInfo),
192
292
  lastError: payload.last_error ?? null,
193
293
  createdAt: payload.created_at,
194
294
  stoppedAt: payload.stopped_at ?? null
195
295
  });
196
- var toExecResponse = (payload) => ({
296
+ var toExecResponse = (payload) => {
297
+ const response = {
298
+ exitCode: payload.exit_code,
299
+ stdout: payload.stdout,
300
+ stderr: payload.stderr
301
+ };
302
+ if (payload.command_id !== void 0) response.commandId = payload.command_id;
303
+ if (payload.duration_ms !== void 0) response.durationMs = payload.duration_ms;
304
+ if (payload.timed_out !== void 0) response.timedOut = payload.timed_out;
305
+ return response;
306
+ };
307
+ var toCommandHistoryEntry = (payload) => ({
308
+ commandId: payload.command_id,
309
+ source: payload.source,
310
+ status: payload.status,
311
+ startedAt: payload.started_at,
312
+ endedAt: payload.ended_at,
313
+ durationMs: payload.duration_ms,
314
+ timeoutSeconds: payload.timeout_seconds,
197
315
  exitCode: payload.exit_code,
198
- stdout: payload.stdout,
199
- stderr: payload.stderr
316
+ stdoutBytes: payload.stdout_bytes,
317
+ stderrBytes: payload.stderr_bytes,
318
+ errorType: payload.error_type
200
319
  });
320
+ var toTerminalConnectionInfo = (payload) => {
321
+ const separator = payload.gateway_url.includes("?") ? "&" : "?";
322
+ return {
323
+ terminalId: payload.terminal_id,
324
+ gatewayUrl: payload.gateway_url,
325
+ url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
326
+ token: payload.token,
327
+ expiresAt: payload.expires_at,
328
+ headers: {},
329
+ firstMessage: ""
330
+ };
331
+ };
201
332
  var toSandboxTemplateInfo = (payload) => ({
202
333
  id: payload.id,
203
334
  displayName: payload.display_name,
@@ -208,6 +339,80 @@ var toSandboxTemplateInfo = (payload) => ({
208
339
  version: payload.version ?? null,
209
340
  experimental: payload.experimental
210
341
  });
342
+ var diskUnitsToMb = {
343
+ "": 1,
344
+ m: 1,
345
+ mb: 1,
346
+ mib: 1,
347
+ g: 1024,
348
+ gb: 1024,
349
+ gib: 1024,
350
+ t: 1024 * 1024,
351
+ tb: 1024 * 1024,
352
+ tib: 1024 * 1024
353
+ };
354
+ var isAsciiDigit = (char) => char >= "0" && char <= "9";
355
+ var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
356
+ var isSeparatorWhitespace = (char) => char === " " || char === " ";
357
+ var parseDiskString = (disk) => {
358
+ const value = disk.trim();
359
+ if (!value) {
360
+ return void 0;
361
+ }
362
+ let index = 0;
363
+ let digitCount = 0;
364
+ let hasDecimalPoint = false;
365
+ while (index < value.length) {
366
+ const char = value[index];
367
+ if (isAsciiDigit(char)) {
368
+ digitCount += 1;
369
+ index += 1;
370
+ continue;
371
+ }
372
+ if (char === "." && !hasDecimalPoint) {
373
+ hasDecimalPoint = true;
374
+ index += 1;
375
+ continue;
376
+ }
377
+ break;
378
+ }
379
+ if (digitCount === 0 || value[index - 1] === ".") {
380
+ return void 0;
381
+ }
382
+ const amount = value.slice(0, index);
383
+ while (index < value.length && isSeparatorWhitespace(value[index])) {
384
+ index += 1;
385
+ }
386
+ const unit = value.slice(index);
387
+ if ([...unit].some((char) => !isAsciiLetter(char))) {
388
+ return void 0;
389
+ }
390
+ return { amount, unit };
391
+ };
392
+ var parseDiskSizeMb = (disk) => {
393
+ if (disk === void 0) {
394
+ return void 0;
395
+ }
396
+ if (typeof disk === "number") {
397
+ if (!Number.isInteger(disk) || disk <= 0) {
398
+ throw new Error("disk as a number must be a whole number of MB.");
399
+ }
400
+ return disk;
401
+ }
402
+ const parsedDisk = parseDiskString(disk);
403
+ if (!parsedDisk) {
404
+ throw new Error("disk must be a size in MB or a string like '2gb'.");
405
+ }
406
+ const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
407
+ if (multiplier === void 0) {
408
+ throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
409
+ }
410
+ const sizeMb = Number(parsedDisk.amount) * multiplier;
411
+ if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
412
+ throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
413
+ }
414
+ return sizeMb;
415
+ };
211
416
  var buildCreateComputerBody = (params) => {
212
417
  if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
213
418
  throw new Error("cpus and vcpus must have the same value when both are provided.");
@@ -215,17 +420,22 @@ var buildCreateComputerBody = (params) => {
215
420
  if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
216
421
  throw new Error("memory and ramMb must have the same value when both are provided.");
217
422
  }
423
+ const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
424
+ if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
425
+ throw new Error("disk and diskSizeMb must have the same value when both are provided.");
426
+ }
218
427
  const body = {};
219
428
  const vcpus = params.vcpus ?? params.cpus;
220
429
  const ramMb = params.ramMb ?? params.memory;
430
+ const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
221
431
  if (vcpus !== void 0) {
222
432
  body.vcpus = vcpus;
223
433
  }
224
434
  if (ramMb !== void 0) {
225
435
  body.ram_mb = ramMb;
226
436
  }
227
- if (params.diskSizeMb !== void 0) {
228
- body.disk_size_mb = params.diskSizeMb;
437
+ if (diskSizeMb !== void 0) {
438
+ body.disk_size_mb = diskSizeMb;
229
439
  }
230
440
  if (params.image !== void 0) {
231
441
  body.image = params.image;
@@ -238,11 +448,104 @@ var buildCreateComputerBody = (params) => {
238
448
  }
239
449
  return body;
240
450
  };
241
- var computersPath = (path) => `/v1/computers${path}`;
451
+ var computersPath = (path2) => `/v1/computers${path2}`;
242
452
  var pickOverrides = (options) => ({
243
453
  headers: options?.headers,
244
454
  signal: options?.signal
245
455
  });
456
+ var optionalNumber = (value) => typeof value === "number" ? value : void 0;
457
+ var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
458
+ var parseExecStreamEvent = (value) => {
459
+ if (!value || typeof value !== "object") {
460
+ throw new Error("Celesto returned an invalid command stream event.");
461
+ }
462
+ const event = value;
463
+ if (event.type === "stdout" || event.type === "stderr") {
464
+ if (typeof event.data !== "string") {
465
+ throw new Error("Celesto returned command output without text data.");
466
+ }
467
+ return { type: event.type, data: event.data };
468
+ }
469
+ if (event.type === "started") {
470
+ if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
471
+ throw new Error("Celesto returned an invalid command-start event.");
472
+ }
473
+ return {
474
+ type: "started",
475
+ commandId: event.command_id,
476
+ startedAtUnixMs: event.started_at_unix_ms,
477
+ timeoutSeconds: event.timeout_seconds
478
+ };
479
+ }
480
+ if (event.type === "exit") {
481
+ if (typeof event.exit_code !== "number") {
482
+ throw new Error("Celesto returned an invalid command-exit event.");
483
+ }
484
+ const result = {
485
+ type: "exit",
486
+ exitCode: event.exit_code
487
+ };
488
+ if (typeof event.command_id === "string") result.commandId = event.command_id;
489
+ const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
490
+ const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
491
+ const durationMs = optionalNumber(event.duration_ms);
492
+ const timedOut = optionalBoolean(event.timed_out);
493
+ if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
494
+ if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
495
+ if (durationMs !== void 0) result.durationMs = durationMs;
496
+ if (timedOut !== void 0) result.timedOut = timedOut;
497
+ return result;
498
+ }
499
+ throw new Error("Celesto returned an unknown command stream event.");
500
+ };
501
+ var parseSseDataLine = (line) => {
502
+ const text = line.trim();
503
+ if (!text || !text.startsWith("data:")) {
504
+ return void 0;
505
+ }
506
+ const data = text.slice("data:".length).trim();
507
+ if (!data || data === "[DONE]") {
508
+ return void 0;
509
+ }
510
+ try {
511
+ return parseExecStreamEvent(JSON.parse(data));
512
+ } catch (error) {
513
+ if (error instanceof SyntaxError) {
514
+ throw new Error("Celesto returned malformed JSON in the command stream.");
515
+ }
516
+ throw error;
517
+ }
518
+ };
519
+ var createManagedSignal = (signal, timeoutMs) => {
520
+ if (!timeoutMs || timeoutMs <= 0) {
521
+ return { signal, cleanup: () => {
522
+ } };
523
+ }
524
+ const controller = new AbortController();
525
+ const abort = () => controller.abort();
526
+ if (signal?.aborted) {
527
+ abort();
528
+ } else {
529
+ signal?.addEventListener("abort", abort, { once: true });
530
+ }
531
+ const timer = setTimeout(abort, timeoutMs);
532
+ return {
533
+ signal: controller.signal,
534
+ cleanup: () => {
535
+ clearTimeout(timer);
536
+ signal?.removeEventListener("abort", abort);
537
+ }
538
+ };
539
+ };
540
+ var toNetworkError = (error) => {
541
+ if (error instanceof CelestoNetworkError) return error;
542
+ const cause = error instanceof Error ? error : new Error(String(error));
543
+ return new CelestoNetworkError(cause.message, cause);
544
+ };
545
+ var withFallbackCommandId = (event, commandId) => {
546
+ if (event.type !== "exit" || event.commandId || !commandId) return event;
547
+ return { ...event, commandId };
548
+ };
246
549
  var ComputersClient = class {
247
550
  constructor(config) {
248
551
  this.config = config;
@@ -266,11 +569,17 @@ var ComputersClient = class {
266
569
  });
267
570
  return data.map(toSandboxTemplateInfo);
268
571
  }
269
- async list(options) {
572
+ async list(params = {}, options) {
270
573
  const ctx = buildRequestContext(this.config);
271
574
  const data = await request(ctx, {
272
575
  method: "GET",
273
576
  path: computersPath(""),
577
+ query: {
578
+ status: params.status,
579
+ template_id: params.templateId,
580
+ project_id: params.projectId,
581
+ limit: params.limit
582
+ },
274
583
  ...pickOverrides(options)
275
584
  });
276
585
  return {
@@ -288,17 +597,113 @@ var ComputersClient = class {
288
597
  return toComputerInfo(data);
289
598
  }
290
599
  async exec(computerId, command, params = {}, options) {
600
+ const ctx = buildRequestContext(this.config);
601
+ const managedSignal = createManagedSignal(
602
+ params.signal ?? options?.signal,
603
+ this.config.timeoutMs
604
+ );
605
+ try {
606
+ const data = await request(ctx, {
607
+ method: "POST",
608
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
609
+ body: {
610
+ command,
611
+ timeout: params.timeout ?? 30
612
+ },
613
+ headers: options?.headers,
614
+ signal: managedSignal.signal
615
+ });
616
+ return toExecResponse(data);
617
+ } finally {
618
+ managedSignal.cleanup();
619
+ }
620
+ }
621
+ async *execStream(computerId, command, params = {}, options) {
622
+ const ctx = buildRequestContext(this.config);
623
+ const managedSignal = createManagedSignal(
624
+ params.signal ?? options?.signal,
625
+ this.config.timeoutMs
626
+ );
627
+ let reader;
628
+ let completed = false;
629
+ try {
630
+ const response = await requestStream(ctx, {
631
+ method: "POST",
632
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
633
+ body: {
634
+ command,
635
+ timeout: params.timeout ?? 30
636
+ },
637
+ headers: options?.headers,
638
+ signal: managedSignal.signal
639
+ });
640
+ if (!response.body) {
641
+ throw new Error("Celesto did not return a command output stream.");
642
+ }
643
+ const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
644
+ reader = response.body.getReader();
645
+ const decoder = new TextDecoder();
646
+ let buffer = "";
647
+ while (true) {
648
+ let chunk;
649
+ try {
650
+ chunk = await reader.read();
651
+ } catch (error) {
652
+ throw toNetworkError(error);
653
+ }
654
+ if (chunk.done) {
655
+ completed = true;
656
+ buffer += decoder.decode();
657
+ break;
658
+ }
659
+ buffer += decoder.decode(chunk.value, { stream: true });
660
+ let newlineIndex = buffer.indexOf("\n");
661
+ while (newlineIndex !== -1) {
662
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
663
+ buffer = buffer.slice(newlineIndex + 1);
664
+ const parsed = parseSseDataLine(line);
665
+ if (parsed) {
666
+ const event = withFallbackCommandId(parsed, responseCommandId);
667
+ yield event;
668
+ if (event.type === "exit") return;
669
+ }
670
+ newlineIndex = buffer.indexOf("\n");
671
+ }
672
+ }
673
+ if (buffer) {
674
+ const parsed = parseSseDataLine(buffer);
675
+ if (parsed) {
676
+ const event = withFallbackCommandId(parsed, responseCommandId);
677
+ yield event;
678
+ if (event.type === "exit") return;
679
+ }
680
+ }
681
+ throw new Error("Command stream ended before Celesto returned an exit status.");
682
+ } finally {
683
+ if (reader) {
684
+ if (!completed) {
685
+ try {
686
+ await reader.cancel();
687
+ } catch {
688
+ }
689
+ }
690
+ reader.releaseLock();
691
+ }
692
+ managedSignal.cleanup();
693
+ }
694
+ }
695
+ async listCommandHistory(computerId, params = {}, options) {
291
696
  const ctx = buildRequestContext(this.config);
292
697
  const data = await request(ctx, {
293
- method: "POST",
294
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
295
- body: {
296
- command,
297
- timeout: params.timeout ?? 30
298
- },
698
+ method: "GET",
699
+ path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
700
+ query: { limit: params.limit },
299
701
  ...pickOverrides(options)
300
702
  });
301
- return toExecResponse(data);
703
+ return {
704
+ commands: data.commands.map(toCommandHistoryEntry),
705
+ count: data.count
706
+ };
302
707
  }
303
708
  async stop(computerId, options) {
304
709
  const ctx = buildRequestContext(this.config);
@@ -327,47 +732,215 @@ var ComputersClient = class {
327
732
  });
328
733
  return toComputerInfo(data);
329
734
  }
330
- /**
331
- * Get connection info for opening a WebSocket terminal session.
332
- *
333
- * Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
334
- * The name is resolved to the canonical ID via a GET call — the backend's
335
- * WebSocket endpoint does not resolve names on its own.
336
- *
337
- * Returns the URL, headers, and first message needed to open the connection
338
- * with any WebSocket library of your choice.
339
- *
340
- * @example
341
- * ```ts
342
- * const conn = await celesto.computers.getTerminalConnection("my-computer");
343
- * const ws = new WebSocket(conn.url, { headers: conn.headers });
344
- * ws.on("open", () => ws.send(conn.firstMessage));
345
- * ws.on("message", (data) => process.stdout.write(data));
346
- * ```
347
- */
348
- async getTerminalConnection(computerIdOrName) {
349
- const info = await this.get(computerIdOrName);
735
+ async publishPort(computerId, port = 8e3, options) {
350
736
  const ctx = buildRequestContext(this.config);
351
- if (!ctx.token) {
352
- throw new Error("A token is required for terminal connections");
353
- }
354
- const wsBase = ctx.baseUrl.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
355
- const url = `${wsBase}/v1/computers/${encodeURIComponent(info.id)}/terminal`;
356
- const headers = {
357
- Authorization: `Bearer ${ctx.token}`
737
+ const data = await request(ctx, {
738
+ method: "POST",
739
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
740
+ body: { port },
741
+ ...pickOverrides(options)
742
+ });
743
+ return toPublishedPortInfo(data);
744
+ }
745
+ async listPublishedPorts(computerId, options) {
746
+ const ctx = buildRequestContext(this.config);
747
+ const data = await request(ctx, {
748
+ method: "GET",
749
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
750
+ ...pickOverrides(options)
751
+ });
752
+ return data.map(toPublishedPortInfo);
753
+ }
754
+ async unpublishPort(computerId, port = 8e3, options) {
755
+ const ctx = buildRequestContext(this.config);
756
+ const data = await request(ctx, {
757
+ method: "DELETE",
758
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports/${port}`),
759
+ ...pickOverrides(options)
760
+ });
761
+ return toPublishedPortInfo(data);
762
+ }
763
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
764
+ async createTerminalSession(computerIdOrName, options) {
765
+ const ctx = buildRequestContext(this.config);
766
+ const data = await request(ctx, {
767
+ method: "POST",
768
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
769
+ ...pickOverrides(options)
770
+ });
771
+ return toTerminalConnectionInfo(data);
772
+ }
773
+ /** @deprecated Use createTerminalSession(). */
774
+ async getTerminalConnection(computerIdOrName, options) {
775
+ return this.createTerminalSession(computerIdOrName, options);
776
+ }
777
+ };
778
+
779
+ // src/computers/computer.ts
780
+ var defaultConfig = () => ({
781
+ token: typeof process !== "undefined" ? process.env.CELESTO_API_KEY : void 0
782
+ });
783
+ var Computer = class _Computer {
784
+ constructor(client, info) {
785
+ this.client = client;
786
+ this.info = info;
787
+ }
788
+ /** Create a new computer and return an object with methods on it. */
789
+ static async create(params = {}, config) {
790
+ const client = new ComputersClient(await resolveClientConfig(config));
791
+ const info = await client.create(params);
792
+ return new _Computer(client, info);
793
+ }
794
+ /** Load an existing computer by name or ID. */
795
+ static async get(computerIdOrName, config) {
796
+ const client = new ComputersClient(await resolveClientConfig(config));
797
+ const info = await client.get(computerIdOrName);
798
+ return new _Computer(client, info);
799
+ }
800
+ /** List computers in the current account. */
801
+ static async list(params = {}, config) {
802
+ const client = new ComputersClient(await resolveClientConfig(config));
803
+ const response = await client.list(params);
804
+ return response.computers.map((info) => new _Computer(client, info));
805
+ }
806
+ /** List available computer templates. */
807
+ static async listTemplates(config) {
808
+ const client = new ComputersClient(await resolveClientConfig(config));
809
+ return client.listTemplates();
810
+ }
811
+ /** Wrap an existing API response in the convenience object. */
812
+ static fromInfo(info, config = defaultConfig()) {
813
+ return new _Computer(new ComputersClient(config), info);
814
+ }
815
+ get id() {
816
+ return this.info.id;
817
+ }
818
+ get name() {
819
+ return this.info.name;
820
+ }
821
+ get status() {
822
+ return this.info.status;
823
+ }
824
+ get vcpus() {
825
+ return this.info.vcpus;
826
+ }
827
+ get ramMb() {
828
+ return this.info.ramMb;
829
+ }
830
+ get diskSizeMb() {
831
+ return this.info.diskSizeMb;
832
+ }
833
+ get image() {
834
+ return this.info.image;
835
+ }
836
+ get templateId() {
837
+ return this.info.templateId;
838
+ }
839
+ get templateVersion() {
840
+ return this.info.templateVersion;
841
+ }
842
+ get connection() {
843
+ return this.info.connection;
844
+ }
845
+ get publishedPorts() {
846
+ return this.info.publishedPorts;
847
+ }
848
+ get lastError() {
849
+ return this.info.lastError;
850
+ }
851
+ get createdAt() {
852
+ return this.info.createdAt;
853
+ }
854
+ get stoppedAt() {
855
+ return this.info.stoppedAt;
856
+ }
857
+ /** Get one field from the latest computer data. */
858
+ get(key) {
859
+ return this.info[key];
860
+ }
861
+ /** Return a copy of the latest computer data. */
862
+ toJSON() {
863
+ return { ...this.info };
864
+ }
865
+ /** Reload this computer from Celesto. */
866
+ async refresh() {
867
+ this.info = await this.client.get(this.id);
868
+ return this;
869
+ }
870
+ /** Run a shell command on this computer. */
871
+ async run(command, params = {}) {
872
+ return this.client.exec(this.id, command, params);
873
+ }
874
+ /** Alias for run(). */
875
+ async exec(command, params = {}) {
876
+ return this.run(command, params);
877
+ }
878
+ /** Run a shell command and stream output and exit events as they arrive. */
879
+ runStream(command, params = {}) {
880
+ return this.client.execStream(this.id, command, params);
881
+ }
882
+ /** Alias for runStream(). */
883
+ execStream(command, params = {}) {
884
+ return this.runStream(command, params);
885
+ }
886
+ /** List recent commands executed on this computer. */
887
+ async listCommandHistory(params = {}) {
888
+ return this.client.listCommandHistory(this.id, params);
889
+ }
890
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
891
+ async createTerminalSession() {
892
+ return this.client.createTerminalSession(this.id);
893
+ }
894
+ /** @deprecated Use createTerminalSession(). */
895
+ async getTerminalConnection() {
896
+ return this.createTerminalSession();
897
+ }
898
+ /** Stop this computer and update the local data. */
899
+ async stop() {
900
+ this.info = await this.client.stop(this.id);
901
+ return this;
902
+ }
903
+ /** Start this computer and update the local data. */
904
+ async start() {
905
+ this.info = await this.client.start(this.id);
906
+ return this;
907
+ }
908
+ /** Delete this computer and update the local data. */
909
+ async delete() {
910
+ this.info = await this.client.delete(this.id);
911
+ return this;
912
+ }
913
+ /** Publish a port and return its public URL when the API provides one. */
914
+ async publishPort(port = 8e3) {
915
+ const published = await this.client.publishPort(this.id, port);
916
+ const existing = this.info.publishedPorts ?? [];
917
+ this.info = {
918
+ ...this.info,
919
+ publishedPorts: [...existing.filter((item) => item.port !== published.port), published]
358
920
  };
359
- if (ctx.organizationId) {
360
- headers["X-Current-Organization"] = ctx.organizationId;
361
- }
362
- return {
363
- url,
364
- headers,
365
- firstMessage: JSON.stringify({ token: ctx.token })
921
+ return published.url ?? null;
922
+ }
923
+ /** List public ports for this computer. */
924
+ async listPublishedPorts() {
925
+ const publishedPorts = await this.client.listPublishedPorts(this.id);
926
+ this.info = { ...this.info, publishedPorts };
927
+ return publishedPorts;
928
+ }
929
+ /** Remove a public port route. */
930
+ async unpublishPort(port = 8e3) {
931
+ const unpublished = await this.client.unpublishPort(this.id, port);
932
+ this.info = {
933
+ ...this.info,
934
+ publishedPorts: (this.info.publishedPorts ?? []).filter((item) => item.port !== port)
366
935
  };
936
+ return unpublished;
367
937
  }
368
938
  };
369
939
  // Annotate the CommonJS export names for ESM import in node:
370
940
  0 && (module.exports = {
371
- ComputersClient
941
+ Computer,
942
+ MISSING_CREDENTIALS_MESSAGE,
943
+ resolveCelestoApiKey,
944
+ resolveClientConfig
372
945
  });
373
946
  //# sourceMappingURL=index.cjs.map