@celestoai/sdk 0.1.3 → 0.1.5

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.
Files changed (37) hide show
  1. package/README.md +246 -10
  2. package/dist/agents/index.cjs +1226 -0
  3. package/dist/agents/index.cjs.map +1 -0
  4. package/dist/agents/index.d.cts +2 -0
  5. package/dist/agents/index.d.ts +2 -0
  6. package/dist/agents/index.js +60 -0
  7. package/dist/agents/index.js.map +1 -0
  8. package/dist/{chunk-LPTIN7LO.js → chunk-52TE4RZV.js} +345 -58
  9. package/dist/chunk-52TE4RZV.js.map +1 -0
  10. package/dist/chunk-6Y2YZCPU.js +1007 -0
  11. package/dist/chunk-6Y2YZCPU.js.map +1 -0
  12. package/dist/{chunk-4KVRJSVJ.js → chunk-P7F52CSQ.js} +2 -2
  13. package/dist/{chunk-N3HU6ONW.js → chunk-THPVQCTE.js} +41 -6
  14. package/dist/chunk-THPVQCTE.js.map +1 -0
  15. package/dist/computers/index.cjs +407 -74
  16. package/dist/computers/index.cjs.map +1 -1
  17. package/dist/computers/index.d.cts +96 -15
  18. package/dist/computers/index.d.ts +96 -15
  19. package/dist/computers/index.js +10 -4
  20. package/dist/{config-BTTpuv_b.d.cts → config-dDPvsH-K.d.cts} +18 -1
  21. package/dist/{config-BTTpuv_b.d.ts → config-dDPvsH-K.d.ts} +18 -1
  22. package/dist/gatekeeper/index.cjs +14 -4
  23. package/dist/gatekeeper/index.cjs.map +1 -1
  24. package/dist/gatekeeper/index.d.cts +1 -1
  25. package/dist/gatekeeper/index.d.ts +1 -1
  26. package/dist/gatekeeper/index.js +2 -2
  27. package/dist/index-Cii1_OFg.d.ts +696 -0
  28. package/dist/index-CsEA7qMF.d.cts +696 -0
  29. package/dist/index.cjs +1412 -64
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +3 -21
  32. package/dist/index.d.ts +3 -21
  33. package/dist/index.js +61 -5
  34. package/package.json +11 -3
  35. package/dist/chunk-LPTIN7LO.js.map +0 -1
  36. package/dist/chunk-N3HU6ONW.js.map +0 -1
  37. /package/dist/{chunk-4KVRJSVJ.js.map → chunk-P7F52CSQ.js.map} +0 -0
@@ -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
- Computer: () => Computer
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 {
@@ -44,12 +52,13 @@ var CelestoError = class extends Error {
44
52
  }
45
53
  };
46
54
  var CelestoApiError = class extends CelestoError {
47
- constructor(message, status, data, requestId) {
55
+ constructor(message, status, data, requestId, headers) {
48
56
  super(message);
49
57
  this.name = "CelestoApiError";
50
58
  this.status = status;
51
59
  this.data = data;
52
60
  this.requestId = requestId;
61
+ this.headers = headers;
53
62
  }
54
63
  };
55
64
  var CelestoNetworkError = class extends CelestoError {
@@ -60,10 +69,67 @@ var CelestoNetworkError = class extends CelestoError {
60
69
  }
61
70
  };
62
71
 
72
+ // src/core/auth.ts
73
+ var execFile = (0, import_node_util.promisify)(import_node_child_process.execFile);
74
+ var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
75
+ function nonEmpty(value) {
76
+ const trimmed = value?.trim();
77
+ return trimmed ? trimmed : void 0;
78
+ }
79
+ async function readDotEnvApiKey(cwd, readDotEnv) {
80
+ try {
81
+ const contents = await readDotEnv(import_node_path.default.join(cwd, ".env"));
82
+ return nonEmpty((0, import_dotenv.parse)(contents).CELESTO_API_KEY);
83
+ } catch {
84
+ return void 0;
85
+ }
86
+ }
87
+ async function loadCliApiKey() {
88
+ try {
89
+ const { stdout } = await execFile("celesto", ["auth", "token"], {
90
+ encoding: "utf8",
91
+ timeout: 5e3,
92
+ maxBuffer: 64 * 1024
93
+ });
94
+ return nonEmpty(stdout);
95
+ } catch {
96
+ return void 0;
97
+ }
98
+ }
99
+ async function resolveCelestoApiKey(options = {}) {
100
+ const env = options.env ?? process.env;
101
+ const environmentKey = nonEmpty(env.CELESTO_API_KEY);
102
+ if (environmentKey) return environmentKey;
103
+ const dotEnvKey = await readDotEnvApiKey(
104
+ options.cwd ?? process.cwd(),
105
+ options.readDotEnv ?? ((filePath) => (0, import_promises.readFile)(filePath, "utf8"))
106
+ );
107
+ if (dotEnvKey) return dotEnvKey;
108
+ return (options.loadSavedApiKey ?? loadCliApiKey)();
109
+ }
110
+ async function resolveClientConfig(config = {}, options = {}) {
111
+ if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
112
+ const apiKey = await resolveCelestoApiKey(options);
113
+ if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
114
+ return { ...config, token: apiKey };
115
+ }
116
+
117
+ // src/core/config.ts
118
+ var DEFAULT_BASE_URL = "https://api.celesto.ai";
119
+ var buildRequestContext = (config) => ({
120
+ fetch: config.fetch ?? fetch,
121
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
122
+ token: config.token ?? config.apiKey,
123
+ organizationId: config.organizationId,
124
+ userAgent: config.userAgent,
125
+ timeoutMs: config.timeoutMs,
126
+ headers: config.headers
127
+ });
128
+
63
129
  // src/core/http.ts
64
- var joinUrl = (baseUrl, path) => {
130
+ var joinUrl = (baseUrl, path2) => {
65
131
  const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
66
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
132
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
67
133
  return `${trimmedBase}${normalizedPath}`;
68
134
  };
69
135
  var buildQuery = (query) => {
@@ -111,7 +177,7 @@ var extractErrorMessage = (data, status) => {
111
177
  }
112
178
  return `Request failed with status ${status}`;
113
179
  };
114
- var request = async (ctx, options) => {
180
+ var buildRequestInit = (ctx, options) => {
115
181
  const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
116
182
  const headers = {
117
183
  ...ctx.headers ?? {},
@@ -129,13 +195,16 @@ var request = async (ctx, options) => {
129
195
  const init = {
130
196
  method: options.method,
131
197
  headers,
132
- body: void 0,
133
198
  signal: options.signal
134
199
  };
135
200
  if (options.body !== void 0) {
136
201
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
137
202
  init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
138
203
  }
204
+ return { url, init };
205
+ };
206
+ var request = async (ctx, options) => {
207
+ const { url, init } = buildRequestInit(ctx, options);
139
208
  let timeoutId;
140
209
  let controller;
141
210
  if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
@@ -148,7 +217,13 @@ var request = async (ctx, options) => {
148
217
  const data = await parseResponseBody(response);
149
218
  if (!response.ok) {
150
219
  const message = extractErrorMessage(data, response.status);
151
- throw new CelestoApiError(message, response.status, data, response.headers.get("x-request-id") ?? void 0);
220
+ throw new CelestoApiError(
221
+ message,
222
+ response.status,
223
+ data,
224
+ response.headers.get("x-request-id") ?? void 0,
225
+ response.headers
226
+ );
152
227
  }
153
228
  return data;
154
229
  } catch (err) {
@@ -163,6 +238,30 @@ var request = async (ctx, options) => {
163
238
  }
164
239
  }
165
240
  };
241
+ var requestStream = async (ctx, options) => {
242
+ const { url, init } = buildRequestInit(ctx, options);
243
+ try {
244
+ const response = await ctx.fetch(url, init);
245
+ if (!response.ok) {
246
+ const data = await parseResponseBody(response);
247
+ const message = extractErrorMessage(data, response.status);
248
+ throw new CelestoApiError(
249
+ message,
250
+ response.status,
251
+ data,
252
+ response.headers.get("x-request-id") ?? void 0,
253
+ response.headers
254
+ );
255
+ }
256
+ return response;
257
+ } catch (err) {
258
+ if (err instanceof CelestoApiError) {
259
+ throw err;
260
+ }
261
+ const error = err instanceof Error ? err : new Error(String(err));
262
+ throw new CelestoNetworkError(error.message, error);
263
+ }
264
+ };
166
265
 
167
266
  // src/computers/client.ts
168
267
  var toConnection = (payload) => {
@@ -196,17 +295,50 @@ var toComputerInfo = (payload) => ({
196
295
  image: payload.image,
197
296
  templateId: payload.template_id,
198
297
  templateVersion: payload.template_version ?? null,
298
+ persistentHome: payload.external_volume_enabled ?? false,
299
+ networkPolicy: payload.network_policy ?? { mode: "open" },
199
300
  connection: toConnection(payload.connection),
200
301
  publishedPorts: payload.published_ports?.map(toPublishedPortInfo),
201
302
  lastError: payload.last_error ?? null,
202
303
  createdAt: payload.created_at,
203
304
  stoppedAt: payload.stopped_at ?? null
204
305
  });
205
- var toExecResponse = (payload) => ({
306
+ var toExecResponse = (payload) => {
307
+ const response = {
308
+ exitCode: payload.exit_code,
309
+ stdout: payload.stdout,
310
+ stderr: payload.stderr
311
+ };
312
+ if (payload.command_id !== void 0) response.commandId = payload.command_id;
313
+ if (payload.duration_ms !== void 0) response.durationMs = payload.duration_ms;
314
+ if (payload.timed_out !== void 0) response.timedOut = payload.timed_out;
315
+ return response;
316
+ };
317
+ var toCommandHistoryEntry = (payload) => ({
318
+ commandId: payload.command_id,
319
+ source: payload.source,
320
+ status: payload.status,
321
+ startedAt: payload.started_at,
322
+ endedAt: payload.ended_at,
323
+ durationMs: payload.duration_ms,
324
+ timeoutSeconds: payload.timeout_seconds,
206
325
  exitCode: payload.exit_code,
207
- stdout: payload.stdout,
208
- stderr: payload.stderr
326
+ stdoutBytes: payload.stdout_bytes,
327
+ stderrBytes: payload.stderr_bytes,
328
+ errorType: payload.error_type
209
329
  });
330
+ var toTerminalConnectionInfo = (payload) => {
331
+ const separator = payload.gateway_url.includes("?") ? "&" : "?";
332
+ return {
333
+ terminalId: payload.terminal_id,
334
+ gatewayUrl: payload.gateway_url,
335
+ url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
336
+ token: payload.token,
337
+ expiresAt: payload.expires_at,
338
+ headers: {},
339
+ firstMessage: ""
340
+ };
341
+ };
210
342
  var toSandboxTemplateInfo = (payload) => ({
211
343
  id: payload.id,
212
344
  displayName: payload.display_name,
@@ -303,6 +435,16 @@ var buildCreateComputerBody = (params) => {
303
435
  throw new Error("disk and diskSizeMb must have the same value when both are provided.");
304
436
  }
305
437
  const body = {};
438
+ if (params.networkPolicy !== void 0) {
439
+ const policy = params.networkPolicy;
440
+ if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
441
+ throw new Error('networkPolicy must be {mode: "open"} or {mode: "off"}.');
442
+ }
443
+ if (policy.mode === "off" && params.persistentHome) {
444
+ throw new Error("External volumes require internet access; set persistentHome=false.");
445
+ }
446
+ body.network_policy = { mode: policy.mode };
447
+ }
306
448
  const vcpus = params.vcpus ?? params.cpus;
307
449
  const ramMb = params.ramMb ?? params.memory;
308
450
  const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
@@ -324,13 +466,109 @@ var buildCreateComputerBody = (params) => {
324
466
  if (params.templateVersion !== void 0) {
325
467
  body.template_version = params.templateVersion;
326
468
  }
469
+ if (params.persistentHome !== void 0) {
470
+ body.external_volume_enabled = params.persistentHome;
471
+ }
327
472
  return body;
328
473
  };
329
- var computersPath = (path) => `/v1/computers${path}`;
474
+ var computersPath = (path2) => `/v1/computers${path2}`;
330
475
  var pickOverrides = (options) => ({
331
476
  headers: options?.headers,
332
477
  signal: options?.signal
333
478
  });
479
+ var optionalNumber = (value) => typeof value === "number" ? value : void 0;
480
+ var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
481
+ var parseExecStreamEvent = (value) => {
482
+ if (!value || typeof value !== "object") {
483
+ throw new Error("Celesto returned an invalid command stream event.");
484
+ }
485
+ const event = value;
486
+ if (event.type === "stdout" || event.type === "stderr") {
487
+ if (typeof event.data !== "string") {
488
+ throw new Error("Celesto returned command output without text data.");
489
+ }
490
+ return { type: event.type, data: event.data };
491
+ }
492
+ if (event.type === "started") {
493
+ if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
494
+ throw new Error("Celesto returned an invalid command-start event.");
495
+ }
496
+ return {
497
+ type: "started",
498
+ commandId: event.command_id,
499
+ startedAtUnixMs: event.started_at_unix_ms,
500
+ timeoutSeconds: event.timeout_seconds
501
+ };
502
+ }
503
+ if (event.type === "exit") {
504
+ if (typeof event.exit_code !== "number") {
505
+ throw new Error("Celesto returned an invalid command-exit event.");
506
+ }
507
+ const result = {
508
+ type: "exit",
509
+ exitCode: event.exit_code
510
+ };
511
+ if (typeof event.command_id === "string") result.commandId = event.command_id;
512
+ const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
513
+ const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
514
+ const durationMs = optionalNumber(event.duration_ms);
515
+ const timedOut = optionalBoolean(event.timed_out);
516
+ if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
517
+ if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
518
+ if (durationMs !== void 0) result.durationMs = durationMs;
519
+ if (timedOut !== void 0) result.timedOut = timedOut;
520
+ return result;
521
+ }
522
+ throw new Error("Celesto returned an unknown command stream event.");
523
+ };
524
+ var parseSseDataLine = (line) => {
525
+ const text = line.trim();
526
+ if (!text || !text.startsWith("data:")) {
527
+ return void 0;
528
+ }
529
+ const data = text.slice("data:".length).trim();
530
+ if (!data || data === "[DONE]") {
531
+ return void 0;
532
+ }
533
+ try {
534
+ return parseExecStreamEvent(JSON.parse(data));
535
+ } catch (error) {
536
+ if (error instanceof SyntaxError) {
537
+ throw new Error("Celesto returned malformed JSON in the command stream.");
538
+ }
539
+ throw error;
540
+ }
541
+ };
542
+ var createManagedSignal = (signal, timeoutMs) => {
543
+ if (!timeoutMs || timeoutMs <= 0) {
544
+ return { signal, cleanup: () => {
545
+ } };
546
+ }
547
+ const controller = new AbortController();
548
+ const abort = () => controller.abort();
549
+ if (signal?.aborted) {
550
+ abort();
551
+ } else {
552
+ signal?.addEventListener("abort", abort, { once: true });
553
+ }
554
+ const timer = setTimeout(abort, timeoutMs);
555
+ return {
556
+ signal: controller.signal,
557
+ cleanup: () => {
558
+ clearTimeout(timer);
559
+ signal?.removeEventListener("abort", abort);
560
+ }
561
+ };
562
+ };
563
+ var toNetworkError = (error) => {
564
+ if (error instanceof CelestoNetworkError) return error;
565
+ const cause = error instanceof Error ? error : new Error(String(error));
566
+ return new CelestoNetworkError(cause.message, cause);
567
+ };
568
+ var withFallbackCommandId = (event, commandId) => {
569
+ if (event.type !== "exit" || event.commandId || !commandId) return event;
570
+ return { ...event, commandId };
571
+ };
334
572
  var ComputersClient = class {
335
573
  constructor(config) {
336
574
  this.config = config;
@@ -382,17 +620,113 @@ var ComputersClient = class {
382
620
  return toComputerInfo(data);
383
621
  }
384
622
  async exec(computerId, command, params = {}, options) {
623
+ const ctx = buildRequestContext(this.config);
624
+ const managedSignal = createManagedSignal(
625
+ params.signal ?? options?.signal,
626
+ this.config.timeoutMs
627
+ );
628
+ try {
629
+ const data = await request(ctx, {
630
+ method: "POST",
631
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
632
+ body: {
633
+ command,
634
+ timeout: params.timeout ?? 30
635
+ },
636
+ headers: options?.headers,
637
+ signal: managedSignal.signal
638
+ });
639
+ return toExecResponse(data);
640
+ } finally {
641
+ managedSignal.cleanup();
642
+ }
643
+ }
644
+ async *execStream(computerId, command, params = {}, options) {
645
+ const ctx = buildRequestContext(this.config);
646
+ const managedSignal = createManagedSignal(
647
+ params.signal ?? options?.signal,
648
+ this.config.timeoutMs
649
+ );
650
+ let reader;
651
+ let completed = false;
652
+ try {
653
+ const response = await requestStream(ctx, {
654
+ method: "POST",
655
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
656
+ body: {
657
+ command,
658
+ timeout: params.timeout ?? 30
659
+ },
660
+ headers: options?.headers,
661
+ signal: managedSignal.signal
662
+ });
663
+ if (!response.body) {
664
+ throw new Error("Celesto did not return a command output stream.");
665
+ }
666
+ const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
667
+ reader = response.body.getReader();
668
+ const decoder = new TextDecoder();
669
+ let buffer = "";
670
+ while (true) {
671
+ let chunk;
672
+ try {
673
+ chunk = await reader.read();
674
+ } catch (error) {
675
+ throw toNetworkError(error);
676
+ }
677
+ if (chunk.done) {
678
+ completed = true;
679
+ buffer += decoder.decode();
680
+ break;
681
+ }
682
+ buffer += decoder.decode(chunk.value, { stream: true });
683
+ let newlineIndex = buffer.indexOf("\n");
684
+ while (newlineIndex !== -1) {
685
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
686
+ buffer = buffer.slice(newlineIndex + 1);
687
+ const parsed = parseSseDataLine(line);
688
+ if (parsed) {
689
+ const event = withFallbackCommandId(parsed, responseCommandId);
690
+ yield event;
691
+ if (event.type === "exit") return;
692
+ }
693
+ newlineIndex = buffer.indexOf("\n");
694
+ }
695
+ }
696
+ if (buffer) {
697
+ const parsed = parseSseDataLine(buffer);
698
+ if (parsed) {
699
+ const event = withFallbackCommandId(parsed, responseCommandId);
700
+ yield event;
701
+ if (event.type === "exit") return;
702
+ }
703
+ }
704
+ throw new Error("Command stream ended before Celesto returned an exit status.");
705
+ } finally {
706
+ if (reader) {
707
+ if (!completed) {
708
+ try {
709
+ await reader.cancel();
710
+ } catch {
711
+ }
712
+ }
713
+ reader.releaseLock();
714
+ }
715
+ managedSignal.cleanup();
716
+ }
717
+ }
718
+ async listCommandHistory(computerId, params = {}, options) {
385
719
  const ctx = buildRequestContext(this.config);
386
720
  const data = await request(ctx, {
387
- method: "POST",
388
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
389
- body: {
390
- command,
391
- timeout: params.timeout ?? 30
392
- },
721
+ method: "GET",
722
+ path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
723
+ query: { limit: params.limit },
393
724
  ...pickOverrides(options)
394
725
  });
395
- return toExecResponse(data);
726
+ return {
727
+ commands: data.commands.map(toCommandHistoryEntry),
728
+ count: data.count
729
+ };
396
730
  }
397
731
  async stop(computerId, options) {
398
732
  const ctx = buildRequestContext(this.config);
@@ -449,43 +783,19 @@ var ComputersClient = class {
449
783
  });
450
784
  return toPublishedPortInfo(data);
451
785
  }
452
- /**
453
- * Get connection info for opening a WebSocket terminal session.
454
- *
455
- * Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
456
- * The name is resolved to the canonical ID via a GET call — the backend's
457
- * WebSocket endpoint does not resolve names on its own.
458
- *
459
- * Returns the URL, headers, and first message needed to open the connection
460
- * with any WebSocket library of your choice.
461
- *
462
- * @example
463
- * ```ts
464
- * const conn = await client.getTerminalConnection("my-computer");
465
- * const ws = new WebSocket(conn.url, { headers: conn.headers });
466
- * ws.on("open", () => ws.send(conn.firstMessage));
467
- * ws.on("message", (data) => process.stdout.write(data));
468
- * ```
469
- */
470
- async getTerminalConnection(computerIdOrName) {
471
- const info = await this.get(computerIdOrName);
786
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
787
+ async createTerminalSession(computerIdOrName, options) {
472
788
  const ctx = buildRequestContext(this.config);
473
- if (!ctx.token) {
474
- throw new Error("A token is required for terminal connections");
475
- }
476
- const wsBase = ctx.baseUrl.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
477
- const url = `${wsBase}/v1/computers/${encodeURIComponent(info.id)}/terminal`;
478
- const headers = {
479
- Authorization: `Bearer ${ctx.token}`
480
- };
481
- if (ctx.organizationId) {
482
- headers["X-Current-Organization"] = ctx.organizationId;
483
- }
484
- return {
485
- url,
486
- headers,
487
- firstMessage: JSON.stringify({ token: ctx.token })
488
- };
789
+ const data = await request(ctx, {
790
+ method: "POST",
791
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
792
+ ...pickOverrides(options)
793
+ });
794
+ return toTerminalConnectionInfo(data);
795
+ }
796
+ /** @deprecated Use createTerminalSession(). */
797
+ async getTerminalConnection(computerIdOrName, options) {
798
+ return this.createTerminalSession(computerIdOrName, options);
489
799
  }
490
800
  };
491
801
 
@@ -499,26 +809,26 @@ var Computer = class _Computer {
499
809
  this.info = info;
500
810
  }
501
811
  /** Create a new computer and return an object with methods on it. */
502
- static async create(params = {}, config = defaultConfig()) {
503
- const client = new ComputersClient(config);
812
+ static async create(params = {}, config) {
813
+ const client = new ComputersClient(await resolveClientConfig(config));
504
814
  const info = await client.create(params);
505
815
  return new _Computer(client, info);
506
816
  }
507
817
  /** Load an existing computer by name or ID. */
508
- static async get(computerIdOrName, config = defaultConfig()) {
509
- const client = new ComputersClient(config);
818
+ static async get(computerIdOrName, config) {
819
+ const client = new ComputersClient(await resolveClientConfig(config));
510
820
  const info = await client.get(computerIdOrName);
511
821
  return new _Computer(client, info);
512
822
  }
513
823
  /** List computers in the current account. */
514
- static async list(params = {}, config = defaultConfig()) {
515
- const client = new ComputersClient(config);
824
+ static async list(params = {}, config) {
825
+ const client = new ComputersClient(await resolveClientConfig(config));
516
826
  const response = await client.list(params);
517
827
  return response.computers.map((info) => new _Computer(client, info));
518
828
  }
519
829
  /** List available computer templates. */
520
- static async listTemplates(config = defaultConfig()) {
521
- const client = new ComputersClient(config);
830
+ static async listTemplates(config) {
831
+ const client = new ComputersClient(await resolveClientConfig(config));
522
832
  return client.listTemplates();
523
833
  }
524
834
  /** Wrap an existing API response in the convenience object. */
@@ -588,6 +898,26 @@ var Computer = class _Computer {
588
898
  async exec(command, params = {}) {
589
899
  return this.run(command, params);
590
900
  }
901
+ /** Run a shell command and stream output and exit events as they arrive. */
902
+ runStream(command, params = {}) {
903
+ return this.client.execStream(this.id, command, params);
904
+ }
905
+ /** Alias for runStream(). */
906
+ execStream(command, params = {}) {
907
+ return this.runStream(command, params);
908
+ }
909
+ /** List recent commands executed on this computer. */
910
+ async listCommandHistory(params = {}) {
911
+ return this.client.listCommandHistory(this.id, params);
912
+ }
913
+ /** Create a short-lived direct connection to Celesto's terminal gateway. */
914
+ async createTerminalSession() {
915
+ return this.client.createTerminalSession(this.id);
916
+ }
917
+ /** @deprecated Use createTerminalSession(). */
918
+ async getTerminalConnection() {
919
+ return this.createTerminalSession();
920
+ }
591
921
  /** Stop this computer and update the local data. */
592
922
  async stop() {
593
923
  this.info = await this.client.stop(this.id);
@@ -631,6 +961,9 @@ var Computer = class _Computer {
631
961
  };
632
962
  // Annotate the CommonJS export names for ESM import in node:
633
963
  0 && (module.exports = {
634
- Computer
964
+ Computer,
965
+ MISSING_CREDENTIALS_MESSAGE,
966
+ resolveCelestoApiKey,
967
+ resolveClientConfig
635
968
  });
636
969
  //# sourceMappingURL=index.cjs.map