@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.
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,17 +17,27 @@ 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
21
31
  var src_exports = {};
22
32
  __export(src_exports, {
23
- Celesto: () => Celesto,
24
33
  CelestoApiError: () => CelestoApiError,
25
34
  CelestoError: () => CelestoError,
26
35
  CelestoNetworkError: () => CelestoNetworkError,
27
- ComputersClient: () => ComputersClient,
28
- GatekeeperClient: () => GatekeeperClient
36
+ Computer: () => Computer,
37
+ GatekeeperClient: () => GatekeeperClient,
38
+ MISSING_CREDENTIALS_MESSAGE: () => MISSING_CREDENTIALS_MESSAGE,
39
+ resolveCelestoApiKey: () => resolveCelestoApiKey,
40
+ resolveClientConfig: () => resolveClientConfig
29
41
  });
30
42
  module.exports = __toCommonJS(src_exports);
31
43
 
@@ -66,9 +78,9 @@ var CelestoNetworkError = class extends CelestoError {
66
78
  };
67
79
 
68
80
  // src/core/http.ts
69
- var joinUrl = (baseUrl, path) => {
81
+ var joinUrl = (baseUrl, path2) => {
70
82
  const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
71
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
83
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
72
84
  return `${trimmedBase}${normalizedPath}`;
73
85
  };
74
86
  var buildQuery = (query) => {
@@ -116,7 +128,7 @@ var extractErrorMessage = (data, status) => {
116
128
  }
117
129
  return `Request failed with status ${status}`;
118
130
  };
119
- var request = async (ctx, options) => {
131
+ var buildRequestInit = (ctx, options) => {
120
132
  const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
121
133
  const headers = {
122
134
  ...ctx.headers ?? {},
@@ -134,13 +146,16 @@ var request = async (ctx, options) => {
134
146
  const init = {
135
147
  method: options.method,
136
148
  headers,
137
- body: void 0,
138
149
  signal: options.signal
139
150
  };
140
151
  if (options.body !== void 0) {
141
152
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
142
153
  init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
143
154
  }
155
+ return { url, init };
156
+ };
157
+ var request = async (ctx, options) => {
158
+ const { url, init } = buildRequestInit(ctx, options);
144
159
  let timeoutId;
145
160
  let controller;
146
161
  if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
@@ -168,9 +183,250 @@ var request = async (ctx, options) => {
168
183
  }
169
184
  }
170
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
+ };
209
+
210
+ // src/gatekeeper/client.ts
211
+ var toConnectRequest = (payload) => ({
212
+ subject: payload.subject,
213
+ provider: payload.provider ?? "google_drive",
214
+ project_name: payload.projectName,
215
+ redirect_uri: payload.redirectUri
216
+ });
217
+ var toConnectResponse = (payload) => ({
218
+ status: payload.status,
219
+ oauthUrl: payload.oauth_url ?? void 0,
220
+ connectionId: payload.connection_id ?? void 0
221
+ });
222
+ var toConnection = (payload) => ({
223
+ id: payload.id,
224
+ subject: payload.subject,
225
+ provider: payload.provider,
226
+ projectId: payload.project_id,
227
+ accountEmail: payload.account_email ?? null,
228
+ scopes: payload.scopes ?? [],
229
+ status: payload.status,
230
+ createdAt: payload.created_at,
231
+ updatedAt: payload.updated_at,
232
+ lastUsedAt: payload.last_used_at ?? null,
233
+ accessRules: payload.access_rules ? {
234
+ version: payload.access_rules.version ?? "1",
235
+ allowedFolders: payload.access_rules.allowed_folders ?? [],
236
+ allowedFiles: payload.access_rules.allowed_files ?? [],
237
+ unrestricted: false
238
+ } : null
239
+ });
240
+ var toAccessRules = (payload) => ({
241
+ version: payload.version,
242
+ allowedFolders: payload.allowed_folders ?? [],
243
+ allowedFiles: payload.allowed_files ?? [],
244
+ unrestricted: payload.unrestricted
245
+ });
246
+ var toDriveFile = (payload) => ({
247
+ id: payload.id,
248
+ name: payload.name ?? null,
249
+ mimeType: payload.mime_type ?? null,
250
+ size: payload.size ?? null,
251
+ modifiedTime: payload.modified_time ?? null,
252
+ createdTime: payload.created_time ?? null,
253
+ webViewLink: payload.web_view_link ?? null,
254
+ iconLink: payload.icon_link ?? null,
255
+ thumbnailLink: payload.thumbnail_link ?? null,
256
+ parents: payload.parents ?? null,
257
+ driveId: payload.drive_id ?? null,
258
+ shared: payload.shared ?? null,
259
+ ownedByMe: payload.owned_by_me ?? null
260
+ });
261
+ var gatekeeperPath = (path2) => `/v1/gatekeeper${path2}`;
262
+ var pickOverrides = (options) => ({
263
+ headers: options?.headers,
264
+ signal: options?.signal
265
+ });
266
+ var GatekeeperClient = class {
267
+ constructor(config) {
268
+ this.config = config;
269
+ }
270
+ async connect(payload, options) {
271
+ const ctx = buildRequestContext(this.config);
272
+ const data = await request(ctx, {
273
+ method: "POST",
274
+ path: gatekeeperPath("/connect"),
275
+ body: toConnectRequest(payload),
276
+ ...pickOverrides(options)
277
+ });
278
+ return toConnectResponse(data);
279
+ }
280
+ async listConnections(params, options) {
281
+ const ctx = buildRequestContext(this.config);
282
+ const data = await request(ctx, {
283
+ method: "GET",
284
+ path: gatekeeperPath("/connections"),
285
+ query: {
286
+ project_name: params.projectName,
287
+ status_filter: params.statusFilter
288
+ },
289
+ ...pickOverrides(options)
290
+ });
291
+ return {
292
+ total: data.total,
293
+ data: data.data.map(toConnection)
294
+ };
295
+ }
296
+ async getConnection(connectionId, options) {
297
+ const ctx = buildRequestContext(this.config);
298
+ const data = await request(ctx, {
299
+ method: "GET",
300
+ path: gatekeeperPath(`/connections/${connectionId}`),
301
+ ...pickOverrides(options)
302
+ });
303
+ return toConnection(data);
304
+ }
305
+ async revokeConnection(params, options) {
306
+ const ctx = buildRequestContext(this.config);
307
+ return request(ctx, {
308
+ method: "DELETE",
309
+ path: gatekeeperPath("/connections"),
310
+ query: {
311
+ subject: params.subject,
312
+ project_name: params.projectName,
313
+ provider: params.provider
314
+ },
315
+ ...pickOverrides(options)
316
+ });
317
+ }
318
+ async listDriveFiles(params, options) {
319
+ const ctx = buildRequestContext(this.config);
320
+ const data = await request(ctx, {
321
+ method: "GET",
322
+ path: gatekeeperPath("/connectors/drive/files"),
323
+ query: {
324
+ project_name: params.projectName,
325
+ subject: params.subject,
326
+ page_size: params.pageSize,
327
+ page_token: params.pageToken,
328
+ folder_id: params.folderId,
329
+ query: params.query,
330
+ include_folders: params.includeFolders,
331
+ order_by: params.orderBy
332
+ },
333
+ ...pickOverrides(options)
334
+ });
335
+ return {
336
+ files: data.files.map(toDriveFile),
337
+ nextPageToken: data.next_page_token ?? null
338
+ };
339
+ }
340
+ async getAccessRules(connectionId, options) {
341
+ const ctx = buildRequestContext(this.config);
342
+ const data = await request(ctx, {
343
+ method: "GET",
344
+ path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
345
+ ...pickOverrides(options)
346
+ });
347
+ return toAccessRules(data);
348
+ }
349
+ async updateAccessRules(params, options) {
350
+ const ctx = buildRequestContext(this.config);
351
+ const data = await request(ctx, {
352
+ method: "PUT",
353
+ path: gatekeeperPath("/connections/access-rules"),
354
+ query: {
355
+ subject: params.subject,
356
+ project_name: params.projectName,
357
+ provider: params.provider
358
+ },
359
+ body: {
360
+ allowed_folders: params.accessRules.allowedFolders ?? [],
361
+ allowed_files: params.accessRules.allowedFiles ?? []
362
+ },
363
+ ...pickOverrides(options)
364
+ });
365
+ return toAccessRules(data);
366
+ }
367
+ async clearAccessRules(connectionId, options) {
368
+ const ctx = buildRequestContext(this.config);
369
+ const data = await request(ctx, {
370
+ method: "DELETE",
371
+ path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
372
+ ...pickOverrides(options)
373
+ });
374
+ return toAccessRules(data);
375
+ }
376
+ };
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
+ }
171
427
 
172
428
  // src/computers/client.ts
173
- var toConnection = (payload) => {
429
+ var toConnection2 = (payload) => {
174
430
  if (!payload) {
175
431
  return void 0;
176
432
  }
@@ -183,6 +439,14 @@ var toConnection = (payload) => {
183
439
  }
184
440
  return out;
185
441
  };
442
+ var toPublishedPortInfo = (payload) => ({
443
+ id: payload.id ?? null,
444
+ computerId: payload.computer_id,
445
+ port: payload.port,
446
+ url: payload.url ?? null,
447
+ status: payload.status,
448
+ createdAt: payload.created_at ?? null
449
+ });
186
450
  var toComputerInfo = (payload) => ({
187
451
  id: payload.id,
188
452
  name: payload.name,
@@ -193,16 +457,48 @@ var toComputerInfo = (payload) => ({
193
457
  image: payload.image,
194
458
  templateId: payload.template_id,
195
459
  templateVersion: payload.template_version ?? null,
196
- connection: toConnection(payload.connection),
460
+ connection: toConnection2(payload.connection),
461
+ publishedPorts: payload.published_ports?.map(toPublishedPortInfo),
197
462
  lastError: payload.last_error ?? null,
198
463
  createdAt: payload.created_at,
199
464
  stoppedAt: payload.stopped_at ?? null
200
465
  });
201
- 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,
202
485
  exitCode: payload.exit_code,
203
- stdout: payload.stdout,
204
- stderr: payload.stderr
486
+ stdoutBytes: payload.stdout_bytes,
487
+ stderrBytes: payload.stderr_bytes,
488
+ errorType: payload.error_type
205
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
+ };
206
502
  var toSandboxTemplateInfo = (payload) => ({
207
503
  id: payload.id,
208
504
  displayName: payload.display_name,
@@ -213,6 +509,80 @@ var toSandboxTemplateInfo = (payload) => ({
213
509
  version: payload.version ?? null,
214
510
  experimental: payload.experimental
215
511
  });
512
+ var diskUnitsToMb = {
513
+ "": 1,
514
+ m: 1,
515
+ mb: 1,
516
+ mib: 1,
517
+ g: 1024,
518
+ gb: 1024,
519
+ gib: 1024,
520
+ t: 1024 * 1024,
521
+ tb: 1024 * 1024,
522
+ tib: 1024 * 1024
523
+ };
524
+ var isAsciiDigit = (char) => char >= "0" && char <= "9";
525
+ var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
526
+ var isSeparatorWhitespace = (char) => char === " " || char === " ";
527
+ var parseDiskString = (disk) => {
528
+ const value = disk.trim();
529
+ if (!value) {
530
+ return void 0;
531
+ }
532
+ let index = 0;
533
+ let digitCount = 0;
534
+ let hasDecimalPoint = false;
535
+ while (index < value.length) {
536
+ const char = value[index];
537
+ if (isAsciiDigit(char)) {
538
+ digitCount += 1;
539
+ index += 1;
540
+ continue;
541
+ }
542
+ if (char === "." && !hasDecimalPoint) {
543
+ hasDecimalPoint = true;
544
+ index += 1;
545
+ continue;
546
+ }
547
+ break;
548
+ }
549
+ if (digitCount === 0 || value[index - 1] === ".") {
550
+ return void 0;
551
+ }
552
+ const amount = value.slice(0, index);
553
+ while (index < value.length && isSeparatorWhitespace(value[index])) {
554
+ index += 1;
555
+ }
556
+ const unit = value.slice(index);
557
+ if ([...unit].some((char) => !isAsciiLetter(char))) {
558
+ return void 0;
559
+ }
560
+ return { amount, unit };
561
+ };
562
+ var parseDiskSizeMb = (disk) => {
563
+ if (disk === void 0) {
564
+ return void 0;
565
+ }
566
+ if (typeof disk === "number") {
567
+ if (!Number.isInteger(disk) || disk <= 0) {
568
+ throw new Error("disk as a number must be a whole number of MB.");
569
+ }
570
+ return disk;
571
+ }
572
+ const parsedDisk = parseDiskString(disk);
573
+ if (!parsedDisk) {
574
+ throw new Error("disk must be a size in MB or a string like '2gb'.");
575
+ }
576
+ const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
577
+ if (multiplier === void 0) {
578
+ throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
579
+ }
580
+ const sizeMb = Number(parsedDisk.amount) * multiplier;
581
+ if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
582
+ throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
583
+ }
584
+ return sizeMb;
585
+ };
216
586
  var buildCreateComputerBody = (params) => {
217
587
  if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
218
588
  throw new Error("cpus and vcpus must have the same value when both are provided.");
@@ -220,17 +590,22 @@ var buildCreateComputerBody = (params) => {
220
590
  if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
221
591
  throw new Error("memory and ramMb must have the same value when both are provided.");
222
592
  }
593
+ const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
594
+ if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
595
+ throw new Error("disk and diskSizeMb must have the same value when both are provided.");
596
+ }
223
597
  const body = {};
224
598
  const vcpus = params.vcpus ?? params.cpus;
225
599
  const ramMb = params.ramMb ?? params.memory;
600
+ const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
226
601
  if (vcpus !== void 0) {
227
602
  body.vcpus = vcpus;
228
603
  }
229
604
  if (ramMb !== void 0) {
230
605
  body.ram_mb = ramMb;
231
606
  }
232
- if (params.diskSizeMb !== void 0) {
233
- body.disk_size_mb = params.diskSizeMb;
607
+ if (diskSizeMb !== void 0) {
608
+ body.disk_size_mb = diskSizeMb;
234
609
  }
235
610
  if (params.image !== void 0) {
236
611
  body.image = params.image;
@@ -243,11 +618,104 @@ var buildCreateComputerBody = (params) => {
243
618
  }
244
619
  return body;
245
620
  };
246
- var computersPath = (path) => `/v1/computers${path}`;
247
- var pickOverrides = (options) => ({
621
+ var computersPath = (path2) => `/v1/computers${path2}`;
622
+ var pickOverrides2 = (options) => ({
248
623
  headers: options?.headers,
249
624
  signal: options?.signal
250
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
+ };
251
719
  var ComputersClient = class {
252
720
  constructor(config) {
253
721
  this.config = config;
@@ -258,7 +726,7 @@ var ComputersClient = class {
258
726
  method: "POST",
259
727
  path: computersPath(""),
260
728
  body: buildCreateComputerBody(params),
261
- ...pickOverrides(options)
729
+ ...pickOverrides2(options)
262
730
  });
263
731
  return toComputerInfo(data);
264
732
  }
@@ -267,16 +735,22 @@ var ComputersClient = class {
267
735
  const data = await request(ctx, {
268
736
  method: "GET",
269
737
  path: computersPath("/templates"),
270
- ...pickOverrides(options)
738
+ ...pickOverrides2(options)
271
739
  });
272
740
  return data.map(toSandboxTemplateInfo);
273
741
  }
274
- async list(options) {
742
+ async list(params = {}, options) {
275
743
  const ctx = buildRequestContext(this.config);
276
744
  const data = await request(ctx, {
277
745
  method: "GET",
278
746
  path: computersPath(""),
279
- ...pickOverrides(options)
747
+ query: {
748
+ status: params.status,
749
+ template_id: params.templateId,
750
+ project_id: params.projectId,
751
+ limit: params.limit
752
+ },
753
+ ...pickOverrides2(options)
280
754
  });
281
755
  return {
282
756
  computers: data.computers.map(toComputerInfo),
@@ -288,29 +762,125 @@ var ComputersClient = class {
288
762
  const data = await request(ctx, {
289
763
  method: "GET",
290
764
  path: computersPath(`/${encodeURIComponent(computerId)}`),
291
- ...pickOverrides(options)
765
+ ...pickOverrides2(options)
292
766
  });
293
767
  return toComputerInfo(data);
294
768
  }
295
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) {
296
866
  const ctx = buildRequestContext(this.config);
297
867
  const data = await request(ctx, {
298
- method: "POST",
299
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
300
- body: {
301
- command,
302
- timeout: params.timeout ?? 30
303
- },
304
- ...pickOverrides(options)
868
+ method: "GET",
869
+ path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
870
+ query: { limit: params.limit },
871
+ ...pickOverrides2(options)
305
872
  });
306
- return toExecResponse(data);
873
+ return {
874
+ commands: data.commands.map(toCommandHistoryEntry),
875
+ count: data.count
876
+ };
307
877
  }
308
878
  async stop(computerId, options) {
309
879
  const ctx = buildRequestContext(this.config);
310
880
  const data = await request(ctx, {
311
881
  method: "POST",
312
882
  path: computersPath(`/${encodeURIComponent(computerId)}/stop`),
313
- ...pickOverrides(options)
883
+ ...pickOverrides2(options)
314
884
  });
315
885
  return toComputerInfo(data);
316
886
  }
@@ -319,7 +889,7 @@ var ComputersClient = class {
319
889
  const data = await request(ctx, {
320
890
  method: "POST",
321
891
  path: computersPath(`/${encodeURIComponent(computerId)}/start`),
322
- ...pickOverrides(options)
892
+ ...pickOverrides2(options)
323
893
  });
324
894
  return toComputerInfo(data);
325
895
  }
@@ -328,232 +898,223 @@ var ComputersClient = class {
328
898
  const data = await request(ctx, {
329
899
  method: "DELETE",
330
900
  path: computersPath(`/${encodeURIComponent(computerId)}`),
331
- ...pickOverrides(options)
901
+ ...pickOverrides2(options)
332
902
  });
333
903
  return toComputerInfo(data);
334
904
  }
335
- /**
336
- * Get connection info for opening a WebSocket terminal session.
337
- *
338
- * Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
339
- * The name is resolved to the canonical ID via a GET call — the backend's
340
- * WebSocket endpoint does not resolve names on its own.
341
- *
342
- * Returns the URL, headers, and first message needed to open the connection
343
- * with any WebSocket library of your choice.
344
- *
345
- * @example
346
- * ```ts
347
- * const conn = await celesto.computers.getTerminalConnection("my-computer");
348
- * const ws = new WebSocket(conn.url, { headers: conn.headers });
349
- * ws.on("open", () => ws.send(conn.firstMessage));
350
- * ws.on("message", (data) => process.stdout.write(data));
351
- * ```
352
- */
353
- async getTerminalConnection(computerIdOrName) {
354
- const info = await this.get(computerIdOrName);
355
- const ctx = buildRequestContext(this.config);
356
- if (!ctx.token) {
357
- throw new Error("A token is required for terminal connections");
358
- }
359
- const wsBase = ctx.baseUrl.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
360
- const url = `${wsBase}/v1/computers/${encodeURIComponent(info.id)}/terminal`;
361
- const headers = {
362
- Authorization: `Bearer ${ctx.token}`
363
- };
364
- if (ctx.organizationId) {
365
- headers["X-Current-Organization"] = ctx.organizationId;
366
- }
367
- return {
368
- url,
369
- headers,
370
- firstMessage: JSON.stringify({ token: ctx.token })
371
- };
372
- }
373
- };
374
-
375
- // src/gatekeeper/client.ts
376
- var toConnectRequest = (payload) => ({
377
- subject: payload.subject,
378
- provider: payload.provider ?? "google_drive",
379
- project_name: payload.projectName,
380
- redirect_uri: payload.redirectUri
381
- });
382
- var toConnectResponse = (payload) => ({
383
- status: payload.status,
384
- oauthUrl: payload.oauth_url ?? void 0,
385
- connectionId: payload.connection_id ?? void 0
386
- });
387
- var toConnection2 = (payload) => ({
388
- id: payload.id,
389
- subject: payload.subject,
390
- provider: payload.provider,
391
- projectId: payload.project_id,
392
- accountEmail: payload.account_email ?? null,
393
- scopes: payload.scopes ?? [],
394
- status: payload.status,
395
- createdAt: payload.created_at,
396
- updatedAt: payload.updated_at,
397
- lastUsedAt: payload.last_used_at ?? null,
398
- accessRules: payload.access_rules ? {
399
- version: payload.access_rules.version ?? "1",
400
- allowedFolders: payload.access_rules.allowed_folders ?? [],
401
- allowedFiles: payload.access_rules.allowed_files ?? [],
402
- unrestricted: false
403
- } : null
404
- });
405
- var toAccessRules = (payload) => ({
406
- version: payload.version,
407
- allowedFolders: payload.allowed_folders ?? [],
408
- allowedFiles: payload.allowed_files ?? [],
409
- unrestricted: payload.unrestricted
410
- });
411
- var toDriveFile = (payload) => ({
412
- id: payload.id,
413
- name: payload.name ?? null,
414
- mimeType: payload.mime_type ?? null,
415
- size: payload.size ?? null,
416
- modifiedTime: payload.modified_time ?? null,
417
- createdTime: payload.created_time ?? null,
418
- webViewLink: payload.web_view_link ?? null,
419
- iconLink: payload.icon_link ?? null,
420
- thumbnailLink: payload.thumbnail_link ?? null,
421
- parents: payload.parents ?? null,
422
- driveId: payload.drive_id ?? null,
423
- shared: payload.shared ?? null,
424
- ownedByMe: payload.owned_by_me ?? null
425
- });
426
- var gatekeeperPath = (path) => `/v1/gatekeeper${path}`;
427
- var pickOverrides2 = (options) => ({
428
- headers: options?.headers,
429
- signal: options?.signal
430
- });
431
- var GatekeeperClient = class {
432
- constructor(config) {
433
- this.config = config;
434
- }
435
- async connect(payload, options) {
905
+ async publishPort(computerId, port = 8e3, options) {
436
906
  const ctx = buildRequestContext(this.config);
437
907
  const data = await request(ctx, {
438
908
  method: "POST",
439
- path: gatekeeperPath("/connect"),
440
- body: toConnectRequest(payload),
909
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
910
+ body: { port },
441
911
  ...pickOverrides2(options)
442
912
  });
443
- return toConnectResponse(data);
913
+ return toPublishedPortInfo(data);
444
914
  }
445
- async listConnections(params, options) {
915
+ async listPublishedPorts(computerId, options) {
446
916
  const ctx = buildRequestContext(this.config);
447
917
  const data = await request(ctx, {
448
918
  method: "GET",
449
- path: gatekeeperPath("/connections"),
450
- query: {
451
- project_name: params.projectName,
452
- status_filter: params.statusFilter
453
- },
919
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
454
920
  ...pickOverrides2(options)
455
921
  });
456
- return {
457
- total: data.total,
458
- data: data.data.map(toConnection2)
459
- };
922
+ return data.map(toPublishedPortInfo);
460
923
  }
461
- async getConnection(connectionId, options) {
924
+ async unpublishPort(computerId, port = 8e3, options) {
462
925
  const ctx = buildRequestContext(this.config);
463
926
  const data = await request(ctx, {
464
- method: "GET",
465
- path: gatekeeperPath(`/connections/${connectionId}`),
466
- ...pickOverrides2(options)
467
- });
468
- return toConnection2(data);
469
- }
470
- async revokeConnection(params, options) {
471
- const ctx = buildRequestContext(this.config);
472
- return request(ctx, {
473
927
  method: "DELETE",
474
- path: gatekeeperPath("/connections"),
475
- query: {
476
- subject: params.subject,
477
- project_name: params.projectName,
478
- provider: params.provider
479
- },
928
+ path: computersPath(`/${encodeURIComponent(computerId)}/published-ports/${port}`),
480
929
  ...pickOverrides2(options)
481
930
  });
931
+ return toPublishedPortInfo(data);
482
932
  }
483
- async listDriveFiles(params, options) {
933
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
934
+ async createTerminalSession(computerIdOrName, options) {
484
935
  const ctx = buildRequestContext(this.config);
485
936
  const data = await request(ctx, {
486
- method: "GET",
487
- path: gatekeeperPath("/connectors/drive/files"),
488
- query: {
489
- project_name: params.projectName,
490
- subject: params.subject,
491
- page_size: params.pageSize,
492
- page_token: params.pageToken,
493
- folder_id: params.folderId,
494
- query: params.query,
495
- include_folders: params.includeFolders,
496
- order_by: params.orderBy
497
- },
498
- ...pickOverrides2(options)
499
- });
500
- return {
501
- files: data.files.map(toDriveFile),
502
- nextPageToken: data.next_page_token ?? null
503
- };
504
- }
505
- async getAccessRules(connectionId, options) {
506
- const ctx = buildRequestContext(this.config);
507
- const data = await request(ctx, {
508
- method: "GET",
509
- path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
510
- ...pickOverrides2(options)
511
- });
512
- return toAccessRules(data);
513
- }
514
- async updateAccessRules(params, options) {
515
- const ctx = buildRequestContext(this.config);
516
- const data = await request(ctx, {
517
- method: "PUT",
518
- path: gatekeeperPath("/connections/access-rules"),
519
- query: {
520
- subject: params.subject,
521
- project_name: params.projectName,
522
- provider: params.provider
523
- },
524
- body: {
525
- allowed_folders: params.accessRules.allowedFolders ?? [],
526
- allowed_files: params.accessRules.allowedFiles ?? []
527
- },
937
+ method: "POST",
938
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
528
939
  ...pickOverrides2(options)
529
940
  });
530
- return toAccessRules(data);
941
+ return toTerminalConnectionInfo(data);
531
942
  }
532
- async clearAccessRules(connectionId, options) {
533
- const ctx = buildRequestContext(this.config);
534
- const data = await request(ctx, {
535
- method: "DELETE",
536
- path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
537
- ...pickOverrides2(options)
538
- });
539
- return toAccessRules(data);
943
+ /** @deprecated Use createTerminalSession(). */
944
+ async getTerminalConnection(computerIdOrName, options) {
945
+ return this.createTerminalSession(computerIdOrName, options);
540
946
  }
541
947
  };
542
948
 
543
- // src/index.ts
544
- var Celesto = class {
545
- constructor(config) {
546
- this.gatekeeper = new GatekeeperClient(config);
547
- this.computers = new ComputersClient(config);
949
+ // src/computers/computer.ts
950
+ var defaultConfig = () => ({
951
+ token: typeof process !== "undefined" ? process.env.CELESTO_API_KEY : void 0
952
+ });
953
+ var Computer = class _Computer {
954
+ constructor(client, info) {
955
+ this.client = client;
956
+ this.info = info;
957
+ }
958
+ /** Create a new computer and return an object with methods on it. */
959
+ static async create(params = {}, config) {
960
+ const client = new ComputersClient(await resolveClientConfig(config));
961
+ const info = await client.create(params);
962
+ return new _Computer(client, info);
963
+ }
964
+ /** Load an existing computer by name or ID. */
965
+ static async get(computerIdOrName, config) {
966
+ const client = new ComputersClient(await resolveClientConfig(config));
967
+ const info = await client.get(computerIdOrName);
968
+ return new _Computer(client, info);
969
+ }
970
+ /** List computers in the current account. */
971
+ static async list(params = {}, config) {
972
+ const client = new ComputersClient(await resolveClientConfig(config));
973
+ const response = await client.list(params);
974
+ return response.computers.map((info) => new _Computer(client, info));
975
+ }
976
+ /** List available computer templates. */
977
+ static async listTemplates(config) {
978
+ const client = new ComputersClient(await resolveClientConfig(config));
979
+ return client.listTemplates();
980
+ }
981
+ /** Wrap an existing API response in the convenience object. */
982
+ static fromInfo(info, config = defaultConfig()) {
983
+ return new _Computer(new ComputersClient(config), info);
984
+ }
985
+ get id() {
986
+ return this.info.id;
987
+ }
988
+ get name() {
989
+ return this.info.name;
990
+ }
991
+ get status() {
992
+ return this.info.status;
993
+ }
994
+ get vcpus() {
995
+ return this.info.vcpus;
996
+ }
997
+ get ramMb() {
998
+ return this.info.ramMb;
999
+ }
1000
+ get diskSizeMb() {
1001
+ return this.info.diskSizeMb;
1002
+ }
1003
+ get image() {
1004
+ return this.info.image;
1005
+ }
1006
+ get templateId() {
1007
+ return this.info.templateId;
1008
+ }
1009
+ get templateVersion() {
1010
+ return this.info.templateVersion;
1011
+ }
1012
+ get connection() {
1013
+ return this.info.connection;
1014
+ }
1015
+ get publishedPorts() {
1016
+ return this.info.publishedPorts;
1017
+ }
1018
+ get lastError() {
1019
+ return this.info.lastError;
1020
+ }
1021
+ get createdAt() {
1022
+ return this.info.createdAt;
1023
+ }
1024
+ get stoppedAt() {
1025
+ return this.info.stoppedAt;
1026
+ }
1027
+ /** Get one field from the latest computer data. */
1028
+ get(key) {
1029
+ return this.info[key];
1030
+ }
1031
+ /** Return a copy of the latest computer data. */
1032
+ toJSON() {
1033
+ return { ...this.info };
1034
+ }
1035
+ /** Reload this computer from Celesto. */
1036
+ async refresh() {
1037
+ this.info = await this.client.get(this.id);
1038
+ return this;
1039
+ }
1040
+ /** Run a shell command on this computer. */
1041
+ async run(command, params = {}) {
1042
+ return this.client.exec(this.id, command, params);
1043
+ }
1044
+ /** Alias for run(). */
1045
+ async exec(command, params = {}) {
1046
+ return this.run(command, params);
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
+ }
1068
+ /** Stop this computer and update the local data. */
1069
+ async stop() {
1070
+ this.info = await this.client.stop(this.id);
1071
+ return this;
1072
+ }
1073
+ /** Start this computer and update the local data. */
1074
+ async start() {
1075
+ this.info = await this.client.start(this.id);
1076
+ return this;
1077
+ }
1078
+ /** Delete this computer and update the local data. */
1079
+ async delete() {
1080
+ this.info = await this.client.delete(this.id);
1081
+ return this;
1082
+ }
1083
+ /** Publish a port and return its public URL when the API provides one. */
1084
+ async publishPort(port = 8e3) {
1085
+ const published = await this.client.publishPort(this.id, port);
1086
+ const existing = this.info.publishedPorts ?? [];
1087
+ this.info = {
1088
+ ...this.info,
1089
+ publishedPorts: [...existing.filter((item) => item.port !== published.port), published]
1090
+ };
1091
+ return published.url ?? null;
1092
+ }
1093
+ /** List public ports for this computer. */
1094
+ async listPublishedPorts() {
1095
+ const publishedPorts = await this.client.listPublishedPorts(this.id);
1096
+ this.info = { ...this.info, publishedPorts };
1097
+ return publishedPorts;
1098
+ }
1099
+ /** Remove a public port route. */
1100
+ async unpublishPort(port = 8e3) {
1101
+ const unpublished = await this.client.unpublishPort(this.id, port);
1102
+ this.info = {
1103
+ ...this.info,
1104
+ publishedPorts: (this.info.publishedPorts ?? []).filter((item) => item.port !== port)
1105
+ };
1106
+ return unpublished;
548
1107
  }
549
1108
  };
550
1109
  // Annotate the CommonJS export names for ESM import in node:
551
1110
  0 && (module.exports = {
552
- Celesto,
553
1111
  CelestoApiError,
554
1112
  CelestoError,
555
1113
  CelestoNetworkError,
556
- ComputersClient,
557
- GatekeeperClient
1114
+ Computer,
1115
+ GatekeeperClient,
1116
+ MISSING_CREDENTIALS_MESSAGE,
1117
+ resolveCelestoApiKey,
1118
+ resolveClientConfig
558
1119
  });
559
1120
  //# sourceMappingURL=index.cjs.map