@celestoai/sdk 0.1.5 → 0.1.7

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 (40) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +130 -254
  3. package/dist/{chunk-52TE4RZV.js → chunk-3HEUI5UL.js} +341 -306
  4. package/dist/chunk-3HEUI5UL.js.map +1 -0
  5. package/dist/computers/index.cjs +211 -347
  6. package/dist/computers/index.cjs.map +1 -1
  7. package/dist/computers/index.d.cts +1 -239
  8. package/dist/computers/index.d.ts +1 -239
  9. package/dist/computers/index.js +1 -2
  10. package/dist/index-59d7VJXL.d.cts +303 -0
  11. package/dist/index-59d7VJXL.d.ts +303 -0
  12. package/dist/index.cjs +252 -1573
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +22 -4
  15. package/dist/index.d.ts +22 -4
  16. package/dist/index.js +5 -61
  17. package/package.json +25 -22
  18. package/dist/agents/index.cjs +0 -1226
  19. package/dist/agents/index.cjs.map +0 -1
  20. package/dist/agents/index.d.cts +0 -2
  21. package/dist/agents/index.d.ts +0 -2
  22. package/dist/agents/index.js +0 -60
  23. package/dist/agents/index.js.map +0 -1
  24. package/dist/chunk-52TE4RZV.js.map +0 -1
  25. package/dist/chunk-6Y2YZCPU.js +0 -1007
  26. package/dist/chunk-6Y2YZCPU.js.map +0 -1
  27. package/dist/chunk-P7F52CSQ.js +0 -177
  28. package/dist/chunk-P7F52CSQ.js.map +0 -1
  29. package/dist/chunk-THPVQCTE.js +0 -183
  30. package/dist/chunk-THPVQCTE.js.map +0 -1
  31. package/dist/config-dDPvsH-K.d.cts +0 -42
  32. package/dist/config-dDPvsH-K.d.ts +0 -42
  33. package/dist/gatekeeper/index.cjs +0 -348
  34. package/dist/gatekeeper/index.cjs.map +0 -1
  35. package/dist/gatekeeper/index.d.cts +0 -104
  36. package/dist/gatekeeper/index.d.ts +0 -104
  37. package/dist/gatekeeper/index.js +0 -8
  38. package/dist/gatekeeper/index.js.map +0 -1
  39. package/dist/index-Cii1_OFg.d.ts +0 -696
  40. package/dist/index-CsEA7qMF.d.cts +0 -696
@@ -1,18 +1,52 @@
1
- import {
2
- CelestoError,
3
- CelestoNetworkError,
4
- buildRequestContext,
5
- request,
6
- requestStream
7
- } from "./chunk-THPVQCTE.js";
8
-
9
1
  // src/core/auth.ts
10
- import { execFile as execFileCallback } from "child_process";
11
2
  import { readFile } from "fs/promises";
3
+ import { homedir } from "os";
12
4
  import path from "path";
13
- import { promisify } from "util";
14
5
  import { parse } from "dotenv";
15
- var execFile = promisify(execFileCallback);
6
+
7
+ // src/core/config.ts
8
+ var DEFAULT_BASE_URL = "https://api.celesto.ai";
9
+ var buildRequestContext = (config) => ({
10
+ fetch: config.fetch ?? fetch,
11
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
12
+ token: config.token ?? config.apiKey,
13
+ organizationId: config.organizationId,
14
+ userAgent: config.userAgent,
15
+ timeoutMs: config.timeoutMs,
16
+ headers: config.headers
17
+ });
18
+
19
+ // src/core/errors.ts
20
+ var CelestoError = class extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = "CelestoError";
24
+ }
25
+ };
26
+ var CelestoApiError = class extends CelestoError {
27
+ constructor(message, status, data, requestId, headers) {
28
+ super(message);
29
+ this.name = "CelestoApiError";
30
+ this.status = status;
31
+ this.data = data;
32
+ this.requestId = requestId;
33
+ this.headers = headers;
34
+ }
35
+ };
36
+ var CelestoNetworkError = class extends CelestoError {
37
+ constructor(message, cause) {
38
+ super(message);
39
+ this.name = "CelestoNetworkError";
40
+ this.cause = cause;
41
+ }
42
+ };
43
+ function toNetworkError(cause) {
44
+ if (cause instanceof CelestoNetworkError) return cause;
45
+ const error = cause instanceof Error ? cause : new Error(String(cause));
46
+ return new CelestoNetworkError(error.message, error);
47
+ }
48
+
49
+ // src/core/auth.ts
16
50
  var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
17
51
  function nonEmpty(value) {
18
52
  const trimmed = value?.trim();
@@ -26,36 +60,173 @@ async function readDotEnvApiKey(cwd, readDotEnv) {
26
60
  return void 0;
27
61
  }
28
62
  }
29
- async function loadCliApiKey() {
63
+ async function loadCliCredentials(home) {
30
64
  try {
31
- const { stdout } = await execFile("celesto", ["auth", "token"], {
32
- encoding: "utf8",
33
- timeout: 5e3,
34
- maxBuffer: 64 * 1024
35
- });
36
- return nonEmpty(stdout);
65
+ const saved = JSON.parse(await readFile(path.join(home, ".celesto", "credentials"), "utf8"));
66
+ const token = typeof saved?.api_key === "string" ? nonEmpty(saved.api_key) : void 0;
67
+ if (!token) return void 0;
68
+ const url = new URL(nonEmpty(typeof saved.base_url === "string" ? saved.base_url : void 0) ?? DEFAULT_BASE_URL);
69
+ const local = url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
70
+ if (!local && url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return void 0;
71
+ return { token, baseUrl: url.origin };
37
72
  } catch {
38
73
  return void 0;
39
74
  }
40
75
  }
41
- async function resolveCelestoApiKey(options = {}) {
76
+ async function resolveCredentials(options) {
42
77
  const env = options.env ?? process.env;
43
78
  const environmentKey = nonEmpty(env.CELESTO_API_KEY);
44
- if (environmentKey) return environmentKey;
79
+ if (environmentKey) return { token: environmentKey };
45
80
  const dotEnvKey = await readDotEnvApiKey(
46
81
  options.cwd ?? process.cwd(),
47
82
  options.readDotEnv ?? ((filePath) => readFile(filePath, "utf8"))
48
83
  );
49
- if (dotEnvKey) return dotEnvKey;
50
- return (options.loadSavedApiKey ?? loadCliApiKey)();
84
+ if (dotEnvKey) return { token: dotEnvKey };
85
+ if (options.loadSavedApiKey) {
86
+ const token = await options.loadSavedApiKey();
87
+ return token ? { token } : void 0;
88
+ }
89
+ return loadCliCredentials(options.homeDir ?? homedir());
90
+ }
91
+ async function resolveCelestoApiKey(options = {}) {
92
+ return (await resolveCredentials(options))?.token;
51
93
  }
52
94
  async function resolveClientConfig(config = {}, options = {}) {
53
95
  if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
54
- const apiKey = await resolveCelestoApiKey(options);
55
- if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
56
- return { ...config, token: apiKey };
96
+ const credentials = await resolveCredentials(options);
97
+ if (!credentials) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
98
+ if (credentials.baseUrl && config.baseUrl !== void 0 && new URL(config.baseUrl).origin !== credentials.baseUrl) {
99
+ throw new CelestoError("Your saved Celesto key is for a different API URL. Run 'celesto auth login' for this URL or pass an API key explicitly.");
100
+ }
101
+ const baseUrl = config.baseUrl ?? credentials.baseUrl;
102
+ return { ...config, token: credentials.token, ...baseUrl === void 0 ? {} : { baseUrl } };
57
103
  }
58
104
 
105
+ // src/computers/client.ts
106
+ import { randomUUID } from "crypto";
107
+
108
+ // src/core/http.ts
109
+ var joinUrl = (baseUrl, path2) => {
110
+ const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
111
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
112
+ return `${trimmedBase}${normalizedPath}`;
113
+ };
114
+ var buildQuery = (query) => {
115
+ if (!query) {
116
+ return "";
117
+ }
118
+ const params = new URLSearchParams();
119
+ for (const [key, value] of Object.entries(query)) {
120
+ if (value === void 0 || value === null) {
121
+ continue;
122
+ }
123
+ if (Array.isArray(value)) {
124
+ for (const item of value) {
125
+ params.append(key, String(item));
126
+ }
127
+ continue;
128
+ }
129
+ params.set(key, String(value));
130
+ }
131
+ const serialized = params.toString();
132
+ return serialized ? `?${serialized}` : "";
133
+ };
134
+ var parseResponseBody = async (response) => {
135
+ if (response.status === 204) {
136
+ return void 0;
137
+ }
138
+ const contentType = response.headers.get("content-type") ?? "";
139
+ if (contentType.includes("application/json")) {
140
+ return response.json();
141
+ }
142
+ return response.text();
143
+ };
144
+ var extractErrorMessage = (data, status) => {
145
+ if (data && typeof data === "object") {
146
+ const record = data;
147
+ if (typeof record.detail === "string") {
148
+ return record.detail;
149
+ }
150
+ if (typeof record.message === "string") {
151
+ return record.message;
152
+ }
153
+ if (typeof record.error === "string") {
154
+ return record.error;
155
+ }
156
+ }
157
+ return `Request failed with status ${status}`;
158
+ };
159
+ var buildRequestInit = (ctx, options) => {
160
+ const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
161
+ const headers = {
162
+ ...ctx.headers ?? {},
163
+ ...options.headers ?? {}
164
+ };
165
+ if (ctx.token) {
166
+ headers.Authorization = `Bearer ${ctx.token}`;
167
+ }
168
+ if (ctx.organizationId) {
169
+ headers["X-Current-Organization"] = ctx.organizationId;
170
+ }
171
+ if (ctx.userAgent && !headers["User-Agent"]) {
172
+ headers["User-Agent"] = ctx.userAgent;
173
+ }
174
+ const init = {
175
+ method: options.method,
176
+ headers
177
+ };
178
+ if (options.body !== void 0) {
179
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
180
+ init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
181
+ }
182
+ return { url, init };
183
+ };
184
+ function requestDeadline(signal, timeoutMs) {
185
+ if (!timeoutMs || timeoutMs <= 0 || signal?.aborted) return { signal, cleanup: () => {
186
+ } };
187
+ const controller = new AbortController();
188
+ const abort = () => controller.abort(signal?.reason);
189
+ signal?.addEventListener("abort", abort, { once: true });
190
+ const timer = setTimeout(
191
+ () => controller.abort(new DOMException("Celesto request timed out.", "TimeoutError")),
192
+ timeoutMs
193
+ );
194
+ return {
195
+ signal: controller.signal,
196
+ cleanup: () => {
197
+ clearTimeout(timer);
198
+ signal?.removeEventListener("abort", abort);
199
+ }
200
+ };
201
+ }
202
+ var request = async (ctx, options) => {
203
+ const { url, init } = buildRequestInit(ctx, options);
204
+ const { signal, cleanup } = requestDeadline(options.signal, ctx.timeoutMs);
205
+ try {
206
+ if (signal?.aborted) throw signal.reason;
207
+ const response = await ctx.fetch(url, { ...init, signal });
208
+ const data = await parseResponseBody(response);
209
+ if (!response.ok) {
210
+ const message = extractErrorMessage(data, response.status);
211
+ throw new CelestoApiError(
212
+ message,
213
+ response.status,
214
+ data,
215
+ response.headers.get("x-request-id") ?? void 0,
216
+ response.headers
217
+ );
218
+ }
219
+ return data;
220
+ } catch (err) {
221
+ if (err instanceof CelestoApiError) {
222
+ throw err;
223
+ }
224
+ throw toNetworkError(err);
225
+ } finally {
226
+ cleanup();
227
+ }
228
+ };
229
+
59
230
  // src/computers/client.ts
60
231
  var toConnection = (payload) => {
61
232
  if (!payload) {
@@ -82,6 +253,7 @@ var toComputerInfo = (payload) => ({
82
253
  id: payload.id,
83
254
  name: payload.name,
84
255
  status: payload.status,
256
+ ...payload.size_id === void 0 ? {} : { sizeId: payload.size_id },
85
257
  vcpus: payload.vcpus,
86
258
  ramMb: payload.ram_mb,
87
259
  diskSizeMb: payload.disk_size_mb,
@@ -120,18 +292,50 @@ var toCommandHistoryEntry = (payload) => ({
120
292
  stderrBytes: payload.stderr_bytes,
121
293
  errorType: payload.error_type
122
294
  });
295
+ function authenticatedGatewayUrl(gatewayUrl, token) {
296
+ const separator = gatewayUrl.includes("?") ? "&" : "?";
297
+ return `${gatewayUrl}${separator}token=${encodeURIComponent(token)}`;
298
+ }
123
299
  var toTerminalConnectionInfo = (payload) => {
124
- const separator = payload.gateway_url.includes("?") ? "&" : "?";
125
300
  return {
126
301
  terminalId: payload.terminal_id,
127
302
  gatewayUrl: payload.gateway_url,
128
- url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
303
+ url: authenticatedGatewayUrl(payload.gateway_url, payload.token),
129
304
  token: payload.token,
130
305
  expiresAt: payload.expires_at,
131
306
  headers: {},
132
307
  firstMessage: ""
133
308
  };
134
309
  };
310
+ var toBrowserConnectionInfo = (payload) => {
311
+ if (typeof payload !== "object" || payload === null || typeof payload.gateway_url !== "string" || typeof payload.token !== "string" || typeof payload.expires_at !== "string") {
312
+ throw new CelestoError(
313
+ "Celesto did not return browser connection details. Call createBrowserConnection() again."
314
+ );
315
+ }
316
+ const connection = payload;
317
+ return {
318
+ gatewayUrl: connection.gateway_url,
319
+ url: authenticatedGatewayUrl(connection.gateway_url, connection.token),
320
+ token: connection.token,
321
+ expiresAt: connection.expires_at
322
+ };
323
+ };
324
+ var toDisplayConnectionInfo = (payload) => {
325
+ if (typeof payload !== "object" || payload === null || payload.mode !== "read_only" && payload.mode !== "read_write") {
326
+ throw new CelestoError(
327
+ "Celesto did not return display connection details. Call createDisplayConnection() again."
328
+ );
329
+ }
330
+ const connection = payload;
331
+ try {
332
+ return { ...toBrowserConnectionInfo(connection), mode: connection.mode };
333
+ } catch {
334
+ throw new CelestoError(
335
+ "Celesto did not return display connection details. Call createDisplayConnection() again."
336
+ );
337
+ }
338
+ };
135
339
  var toSandboxTemplateInfo = (payload) => ({
136
340
  id: payload.id,
137
341
  displayName: payload.display_name,
@@ -142,92 +346,36 @@ var toSandboxTemplateInfo = (payload) => ({
142
346
  version: payload.version ?? null,
143
347
  experimental: payload.experimental
144
348
  });
145
- var diskUnitsToMb = {
146
- "": 1,
147
- m: 1,
148
- mb: 1,
149
- mib: 1,
150
- g: 1024,
151
- gb: 1024,
152
- gib: 1024,
153
- t: 1024 * 1024,
154
- tb: 1024 * 1024,
155
- tib: 1024 * 1024
156
- };
157
- var isAsciiDigit = (char) => char >= "0" && char <= "9";
158
- var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
159
- var isSeparatorWhitespace = (char) => char === " " || char === " ";
160
- var parseDiskString = (disk) => {
161
- const value = disk.trim();
162
- if (!value) {
163
- return void 0;
164
- }
165
- let index = 0;
166
- let digitCount = 0;
167
- let hasDecimalPoint = false;
168
- while (index < value.length) {
169
- const char = value[index];
170
- if (isAsciiDigit(char)) {
171
- digitCount += 1;
172
- index += 1;
173
- continue;
349
+ var resourceOverrides = ["cpus", "vcpus", "memory", "ramMb", "disk", "diskSizeMb"];
350
+ var createOptions = /* @__PURE__ */ new Set([
351
+ "sizeId",
352
+ "idempotencyKey",
353
+ "networkPolicy",
354
+ "image",
355
+ "templateId",
356
+ "templateVersion",
357
+ "persistentHome",
358
+ ...resourceOverrides
359
+ ]);
360
+ var buildCreateComputerBody = (params) => {
361
+ for (const field of Object.keys(params)) {
362
+ if (field === "size" || field === "size_id") {
363
+ throw new TypeError(`${field} is not a Cloud computer create option. Use sizeId instead.`);
174
364
  }
175
- if (char === "." && !hasDecimalPoint) {
176
- hasDecimalPoint = true;
177
- index += 1;
178
- continue;
365
+ if (!createOptions.has(field)) {
366
+ throw new TypeError(`Unknown computer create option ${JSON.stringify(field)}. Remove it and retry.`);
179
367
  }
180
- break;
181
368
  }
182
- if (digitCount === 0 || value[index - 1] === ".") {
183
- return void 0;
184
- }
185
- const amount = value.slice(0, index);
186
- while (index < value.length && isSeparatorWhitespace(value[index])) {
187
- index += 1;
188
- }
189
- const unit = value.slice(index);
190
- if ([...unit].some((char) => !isAsciiLetter(char))) {
191
- return void 0;
192
- }
193
- return { amount, unit };
194
- };
195
- var parseDiskSizeMb = (disk) => {
196
- if (disk === void 0) {
197
- return void 0;
369
+ if (resourceOverrides.some((field) => params[field] !== void 0)) {
370
+ throw new TypeError("Cloud computers do not accept CPU, memory, or disk overrides. Use sizeId instead.");
198
371
  }
199
- if (typeof disk === "number") {
200
- if (!Number.isInteger(disk) || disk <= 0) {
201
- throw new Error("disk as a number must be a whole number of MB.");
372
+ const body = {};
373
+ if (params.sizeId !== void 0) {
374
+ if (typeof params.sizeId !== "string" || !params.sizeId.trim() || params.sizeId.length > 32) {
375
+ throw new TypeError('Choose a sizeId of 1\u201332 characters, such as "micro".');
202
376
  }
203
- return disk;
204
- }
205
- const parsedDisk = parseDiskString(disk);
206
- if (!parsedDisk) {
207
- throw new Error("disk must be a size in MB or a string like '2gb'.");
208
- }
209
- const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
210
- if (multiplier === void 0) {
211
- throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
212
- }
213
- const sizeMb = Number(parsedDisk.amount) * multiplier;
214
- if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
215
- throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
216
- }
217
- return sizeMb;
218
- };
219
- var buildCreateComputerBody = (params) => {
220
- if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
221
- throw new Error("cpus and vcpus must have the same value when both are provided.");
222
- }
223
- if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
224
- throw new Error("memory and ramMb must have the same value when both are provided.");
377
+ body.size_id = params.sizeId;
225
378
  }
226
- const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
227
- if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
228
- throw new Error("disk and diskSizeMb must have the same value when both are provided.");
229
- }
230
- const body = {};
231
379
  if (params.networkPolicy !== void 0) {
232
380
  const policy = params.networkPolicy;
233
381
  if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
@@ -238,18 +386,6 @@ var buildCreateComputerBody = (params) => {
238
386
  }
239
387
  body.network_policy = { mode: policy.mode };
240
388
  }
241
- const vcpus = params.vcpus ?? params.cpus;
242
- const ramMb = params.ramMb ?? params.memory;
243
- const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
244
- if (vcpus !== void 0) {
245
- body.vcpus = vcpus;
246
- }
247
- if (ramMb !== void 0) {
248
- body.ram_mb = ramMb;
249
- }
250
- if (diskSizeMb !== void 0) {
251
- body.disk_size_mb = diskSizeMb;
252
- }
253
389
  if (params.image !== void 0) {
254
390
  body.image = params.image;
255
391
  }
@@ -269,110 +405,31 @@ var pickOverrides = (options) => ({
269
405
  headers: options?.headers,
270
406
  signal: options?.signal
271
407
  });
272
- var optionalNumber = (value) => typeof value === "number" ? value : void 0;
273
- var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
274
- var parseExecStreamEvent = (value) => {
275
- if (!value || typeof value !== "object") {
276
- throw new Error("Celesto returned an invalid command stream event.");
277
- }
278
- const event = value;
279
- if (event.type === "stdout" || event.type === "stderr") {
280
- if (typeof event.data !== "string") {
281
- throw new Error("Celesto returned command output without text data.");
282
- }
283
- return { type: event.type, data: event.data };
284
- }
285
- if (event.type === "started") {
286
- if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
287
- throw new Error("Celesto returned an invalid command-start event.");
288
- }
289
- return {
290
- type: "started",
291
- commandId: event.command_id,
292
- startedAtUnixMs: event.started_at_unix_ms,
293
- timeoutSeconds: event.timeout_seconds
294
- };
295
- }
296
- if (event.type === "exit") {
297
- if (typeof event.exit_code !== "number") {
298
- throw new Error("Celesto returned an invalid command-exit event.");
299
- }
300
- const result = {
301
- type: "exit",
302
- exitCode: event.exit_code
303
- };
304
- if (typeof event.command_id === "string") result.commandId = event.command_id;
305
- const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
306
- const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
307
- const durationMs = optionalNumber(event.duration_ms);
308
- const timedOut = optionalBoolean(event.timed_out);
309
- if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
310
- if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
311
- if (durationMs !== void 0) result.durationMs = durationMs;
312
- if (timedOut !== void 0) result.timedOut = timedOut;
313
- return result;
314
- }
315
- throw new Error("Celesto returned an unknown command stream event.");
316
- };
317
- var parseSseDataLine = (line) => {
318
- const text = line.trim();
319
- if (!text || !text.startsWith("data:")) {
320
- return void 0;
321
- }
322
- const data = text.slice("data:".length).trim();
323
- if (!data || data === "[DONE]") {
324
- return void 0;
325
- }
326
- try {
327
- return parseExecStreamEvent(JSON.parse(data));
328
- } catch (error) {
329
- if (error instanceof SyntaxError) {
330
- throw new Error("Celesto returned malformed JSON in the command stream.");
331
- }
332
- throw error;
333
- }
334
- };
335
- var createManagedSignal = (signal, timeoutMs) => {
336
- if (!timeoutMs || timeoutMs <= 0) {
337
- return { signal, cleanup: () => {
338
- } };
339
- }
340
- const controller = new AbortController();
341
- const abort = () => controller.abort();
342
- if (signal?.aborted) {
343
- abort();
344
- } else {
345
- signal?.addEventListener("abort", abort, { once: true });
346
- }
347
- const timer = setTimeout(abort, timeoutMs);
348
- return {
349
- signal: controller.signal,
350
- cleanup: () => {
351
- clearTimeout(timer);
352
- signal?.removeEventListener("abort", abort);
353
- }
354
- };
355
- };
356
- var toNetworkError = (error) => {
357
- if (error instanceof CelestoNetworkError) return error;
358
- const cause = error instanceof Error ? error : new Error(String(error));
359
- return new CelestoNetworkError(cause.message, cause);
360
- };
361
- var withFallbackCommandId = (event, commandId) => {
362
- if (event.type !== "exit" || event.commandId || !commandId) return event;
363
- return { ...event, commandId };
364
- };
365
408
  var ComputersClient = class {
366
409
  constructor(config) {
367
410
  this.config = config;
368
411
  }
369
412
  async create(params = {}, options) {
370
413
  const ctx = buildRequestContext(this.config);
371
- const data = await request(ctx, {
414
+ const headers = {};
415
+ let suppliedKey;
416
+ for (const source of [ctx.headers, options?.headers]) {
417
+ for (const [name, value] of Object.entries(source ?? {})) {
418
+ if (name.toLowerCase() === "idempotency-key") suppliedKey = value;
419
+ else headers[name] = value;
420
+ }
421
+ }
422
+ const key = params.idempotencyKey ?? suppliedKey ?? randomUUID();
423
+ if (typeof key !== "string" || !key.trim()) {
424
+ throw new TypeError("idempotencyKey must not be empty. Omit it to generate a key.");
425
+ }
426
+ headers["Idempotency-Key"] = key;
427
+ const data = await request({ ...ctx, headers: void 0 }, {
372
428
  method: "POST",
373
429
  path: computersPath(""),
374
430
  body: buildCreateComputerBody(params),
375
- ...pickOverrides(options)
431
+ headers,
432
+ signal: options?.signal
376
433
  });
377
434
  return toComputerInfo(data);
378
435
  }
@@ -413,100 +470,43 @@ var ComputersClient = class {
413
470
  return toComputerInfo(data);
414
471
  }
415
472
  async exec(computerId, command, params = {}, options) {
416
- const ctx = buildRequestContext(this.config);
417
- const managedSignal = createManagedSignal(
418
- params.signal ?? options?.signal,
419
- this.config.timeoutMs
420
- );
421
- try {
422
- const data = await request(ctx, {
423
- method: "POST",
424
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
425
- body: {
426
- command,
427
- timeout: params.timeout ?? 30
428
- },
429
- headers: options?.headers,
430
- signal: managedSignal.signal
431
- });
432
- return toExecResponse(data);
433
- } finally {
434
- managedSignal.cleanup();
473
+ if (typeof command !== "string" || command.length === 0) {
474
+ throw new TypeError("Provide a non-empty command to run on the Cloud computer.");
435
475
  }
436
- }
437
- async *execStream(computerId, command, params = {}, options) {
438
- const ctx = buildRequestContext(this.config);
439
- const managedSignal = createManagedSignal(
440
- params.signal ?? options?.signal,
441
- this.config.timeoutMs
442
- );
443
- let reader;
444
- let completed = false;
445
- try {
446
- const response = await requestStream(ctx, {
447
- method: "POST",
448
- path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
449
- body: {
450
- command,
451
- timeout: params.timeout ?? 30
452
- },
453
- headers: options?.headers,
454
- signal: managedSignal.signal
455
- });
456
- if (!response.body) {
457
- throw new Error("Celesto did not return a command output stream.");
458
- }
459
- const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
460
- reader = response.body.getReader();
461
- const decoder = new TextDecoder();
462
- let buffer = "";
463
- while (true) {
464
- let chunk;
465
- try {
466
- chunk = await reader.read();
467
- } catch (error) {
468
- throw toNetworkError(error);
469
- }
470
- if (chunk.done) {
471
- completed = true;
472
- buffer += decoder.decode();
473
- break;
474
- }
475
- buffer += decoder.decode(chunk.value, { stream: true });
476
- let newlineIndex = buffer.indexOf("\n");
477
- while (newlineIndex !== -1) {
478
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
479
- buffer = buffer.slice(newlineIndex + 1);
480
- const parsed = parseSseDataLine(line);
481
- if (parsed) {
482
- const event = withFallbackCommandId(parsed, responseCommandId);
483
- yield event;
484
- if (event.type === "exit") return;
485
- }
486
- newlineIndex = buffer.indexOf("\n");
476
+ if (command.length > 1e4) {
477
+ let count = 0;
478
+ for (const _ of command) {
479
+ if (++count > 1e4) {
480
+ throw new TypeError("Cloud commands allow at most 10,000 characters. Shorten the command and retry.");
487
481
  }
488
482
  }
489
- if (buffer) {
490
- const parsed = parseSseDataLine(buffer);
491
- if (parsed) {
492
- const event = withFallbackCommandId(parsed, responseCommandId);
493
- yield event;
494
- if (event.type === "exit") return;
495
- }
496
- }
497
- throw new Error("Command stream ended before Celesto returned an exit status.");
498
- } finally {
499
- if (reader) {
500
- if (!completed) {
501
- try {
502
- await reader.cancel();
503
- } catch {
504
- }
505
- }
506
- reader.releaseLock();
507
- }
508
- managedSignal.cleanup();
509
483
  }
484
+ const timeout = params.timeout ?? 30;
485
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 300) {
486
+ throw new TypeError("Choose a whole-number command timeout between 1 and 300 seconds.");
487
+ }
488
+ const ctx = buildRequestContext(this.config);
489
+ const data = await request(ctx, {
490
+ method: "POST",
491
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
492
+ body: { command, timeout },
493
+ headers: options?.headers,
494
+ signal: params.signal ?? options?.signal
495
+ });
496
+ return toExecResponse(data);
497
+ }
498
+ /** Yield output and exit events after the command has finished. */
499
+ async *execStream(computerId, command, params = {}, options) {
500
+ const { stdout, stderr, exitCode, commandId, durationMs, timedOut } = await this.exec(computerId, command, params, options);
501
+ if (stdout) yield { type: "stdout", data: stdout };
502
+ if (stderr) yield { type: "stderr", data: stderr };
503
+ yield {
504
+ type: "exit",
505
+ exitCode,
506
+ ...commandId == null ? {} : { commandId },
507
+ ...durationMs == null ? {} : { durationMs },
508
+ ...timedOut == null ? {} : { timedOut }
509
+ };
510
510
  }
511
511
  async listCommandHistory(computerId, params = {}, options) {
512
512
  const ctx = buildRequestContext(this.config);
@@ -586,6 +586,27 @@ var ComputersClient = class {
586
586
  });
587
587
  return toTerminalConnectionInfo(data);
588
588
  }
589
+ /** Create a short-lived CDP connection for browser automation. */
590
+ async createBrowserConnection(computerIdOrName, options) {
591
+ const ctx = buildRequestContext(this.config);
592
+ const data = await request(ctx, {
593
+ method: "POST",
594
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/browser`),
595
+ ...pickOverrides(options)
596
+ });
597
+ return toBrowserConnectionInfo(data);
598
+ }
599
+ /** Create a short-lived RFB connection to watch or control the graphical display. */
600
+ async createDisplayConnection(computerIdOrName, params = {}, options) {
601
+ const ctx = buildRequestContext(this.config);
602
+ const data = await request(ctx, {
603
+ method: "POST",
604
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/display`),
605
+ body: params.mode === void 0 ? void 0 : { mode: params.mode },
606
+ ...pickOverrides(options)
607
+ });
608
+ return toDisplayConnectionInfo(data);
609
+ }
589
610
  /** @deprecated Use createTerminalSession(). */
590
611
  async getTerminalConnection(computerIdOrName, options) {
591
612
  return this.createTerminalSession(computerIdOrName, options);
@@ -637,6 +658,9 @@ var Computer = class _Computer {
637
658
  get status() {
638
659
  return this.info.status;
639
660
  }
661
+ get sizeId() {
662
+ return this.info.sizeId;
663
+ }
640
664
  get vcpus() {
641
665
  return this.info.vcpus;
642
666
  }
@@ -691,7 +715,7 @@ var Computer = class _Computer {
691
715
  async exec(command, params = {}) {
692
716
  return this.run(command, params);
693
717
  }
694
- /** Run a shell command and stream output and exit events as they arrive. */
718
+ /** Run a shell command and yield buffered output and exit events after it finishes. */
695
719
  runStream(command, params = {}) {
696
720
  return this.client.execStream(this.id, command, params);
697
721
  }
@@ -707,6 +731,14 @@ var Computer = class _Computer {
707
731
  async createTerminalSession() {
708
732
  return this.client.createTerminalSession(this.id);
709
733
  }
734
+ /** Create a short-lived CDP connection for browser automation. */
735
+ async createBrowserConnection() {
736
+ return this.client.createBrowserConnection(this.id);
737
+ }
738
+ /** Create a short-lived RFB connection to watch or control the graphical display. */
739
+ async createDisplayConnection(params = {}) {
740
+ return this.client.createDisplayConnection(this.id, params);
741
+ }
710
742
  /** @deprecated Use createTerminalSession(). */
711
743
  async getTerminalConnection() {
712
744
  return this.createTerminalSession();
@@ -754,9 +786,12 @@ var Computer = class _Computer {
754
786
  };
755
787
 
756
788
  export {
789
+ CelestoError,
790
+ CelestoApiError,
791
+ CelestoNetworkError,
757
792
  MISSING_CREDENTIALS_MESSAGE,
758
793
  resolveCelestoApiKey,
759
794
  resolveClientConfig,
760
795
  Computer
761
796
  };
762
- //# sourceMappingURL=chunk-52TE4RZV.js.map
797
+ //# sourceMappingURL=chunk-3HEUI5UL.js.map