@celestoai/sdk 0.1.6 → 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 +89 -270
  3. package/dist/{chunk-B4JRBDUO.js → chunk-3HEUI5UL.js} +278 -304
  4. package/dist/chunk-3HEUI5UL.js.map +1 -0
  5. package/dist/computers/index.cjs +148 -345
  6. package/dist/computers/index.cjs.map +1 -1
  7. package/dist/computers/index.d.cts +1 -270
  8. package/dist/computers/index.d.ts +1 -270
  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 +191 -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-6Y2YZCPU.js +0 -1007
  25. package/dist/chunk-6Y2YZCPU.js.map +0 -1
  26. package/dist/chunk-B4JRBDUO.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,35 +60,172 @@ 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 } };
103
+ }
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
+ };
57
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
+ };
58
229
 
59
230
  // src/computers/client.ts
60
231
  var toConnection = (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,
@@ -174,92 +346,36 @@ var toSandboxTemplateInfo = (payload) => ({
174
346
  version: payload.version ?? null,
175
347
  experimental: payload.experimental
176
348
  });
177
- var diskUnitsToMb = {
178
- "": 1,
179
- m: 1,
180
- mb: 1,
181
- mib: 1,
182
- g: 1024,
183
- gb: 1024,
184
- gib: 1024,
185
- t: 1024 * 1024,
186
- tb: 1024 * 1024,
187
- tib: 1024 * 1024
188
- };
189
- var isAsciiDigit = (char) => char >= "0" && char <= "9";
190
- var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
191
- var isSeparatorWhitespace = (char) => char === " " || char === " ";
192
- var parseDiskString = (disk) => {
193
- const value = disk.trim();
194
- if (!value) {
195
- return void 0;
196
- }
197
- let index = 0;
198
- let digitCount = 0;
199
- let hasDecimalPoint = false;
200
- while (index < value.length) {
201
- const char = value[index];
202
- if (isAsciiDigit(char)) {
203
- digitCount += 1;
204
- index += 1;
205
- 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.`);
206
364
  }
207
- if (char === "." && !hasDecimalPoint) {
208
- hasDecimalPoint = true;
209
- index += 1;
210
- continue;
365
+ if (!createOptions.has(field)) {
366
+ throw new TypeError(`Unknown computer create option ${JSON.stringify(field)}. Remove it and retry.`);
211
367
  }
212
- break;
213
- }
214
- if (digitCount === 0 || value[index - 1] === ".") {
215
- return void 0;
216
368
  }
217
- const amount = value.slice(0, index);
218
- while (index < value.length && isSeparatorWhitespace(value[index])) {
219
- index += 1;
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.");
220
371
  }
221
- const unit = value.slice(index);
222
- if ([...unit].some((char) => !isAsciiLetter(char))) {
223
- return void 0;
224
- }
225
- return { amount, unit };
226
- };
227
- var parseDiskSizeMb = (disk) => {
228
- if (disk === void 0) {
229
- return void 0;
230
- }
231
- if (typeof disk === "number") {
232
- if (!Number.isInteger(disk) || disk <= 0) {
233
- 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".');
234
376
  }
235
- return disk;
236
- }
237
- const parsedDisk = parseDiskString(disk);
238
- if (!parsedDisk) {
239
- throw new Error("disk must be a size in MB or a string like '2gb'.");
240
- }
241
- const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
242
- if (multiplier === void 0) {
243
- throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
244
- }
245
- const sizeMb = Number(parsedDisk.amount) * multiplier;
246
- if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
247
- throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
248
- }
249
- return sizeMb;
250
- };
251
- var buildCreateComputerBody = (params) => {
252
- if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
253
- throw new Error("cpus and vcpus must have the same value when both are provided.");
254
- }
255
- if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
256
- throw new Error("memory and ramMb must have the same value when both are provided.");
257
- }
258
- const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
259
- if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
260
- throw new Error("disk and diskSizeMb must have the same value when both are provided.");
377
+ body.size_id = params.sizeId;
261
378
  }
262
- const body = {};
263
379
  if (params.networkPolicy !== void 0) {
264
380
  const policy = params.networkPolicy;
265
381
  if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
@@ -270,18 +386,6 @@ var buildCreateComputerBody = (params) => {
270
386
  }
271
387
  body.network_policy = { mode: policy.mode };
272
388
  }
273
- const vcpus = params.vcpus ?? params.cpus;
274
- const ramMb = params.ramMb ?? params.memory;
275
- const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
276
- if (vcpus !== void 0) {
277
- body.vcpus = vcpus;
278
- }
279
- if (ramMb !== void 0) {
280
- body.ram_mb = ramMb;
281
- }
282
- if (diskSizeMb !== void 0) {
283
- body.disk_size_mb = diskSizeMb;
284
- }
285
389
  if (params.image !== void 0) {
286
390
  body.image = params.image;
287
391
  }
@@ -301,110 +405,31 @@ var pickOverrides = (options) => ({
301
405
  headers: options?.headers,
302
406
  signal: options?.signal
303
407
  });
304
- var optionalNumber = (value) => typeof value === "number" ? value : void 0;
305
- var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
306
- var parseExecStreamEvent = (value) => {
307
- if (!value || typeof value !== "object") {
308
- throw new Error("Celesto returned an invalid command stream event.");
309
- }
310
- const event = value;
311
- if (event.type === "stdout" || event.type === "stderr") {
312
- if (typeof event.data !== "string") {
313
- throw new Error("Celesto returned command output without text data.");
314
- }
315
- return { type: event.type, data: event.data };
316
- }
317
- if (event.type === "started") {
318
- if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
319
- throw new Error("Celesto returned an invalid command-start event.");
320
- }
321
- return {
322
- type: "started",
323
- commandId: event.command_id,
324
- startedAtUnixMs: event.started_at_unix_ms,
325
- timeoutSeconds: event.timeout_seconds
326
- };
327
- }
328
- if (event.type === "exit") {
329
- if (typeof event.exit_code !== "number") {
330
- throw new Error("Celesto returned an invalid command-exit event.");
331
- }
332
- const result = {
333
- type: "exit",
334
- exitCode: event.exit_code
335
- };
336
- if (typeof event.command_id === "string") result.commandId = event.command_id;
337
- const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
338
- const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
339
- const durationMs = optionalNumber(event.duration_ms);
340
- const timedOut = optionalBoolean(event.timed_out);
341
- if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
342
- if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
343
- if (durationMs !== void 0) result.durationMs = durationMs;
344
- if (timedOut !== void 0) result.timedOut = timedOut;
345
- return result;
346
- }
347
- throw new Error("Celesto returned an unknown command stream event.");
348
- };
349
- var parseSseDataLine = (line) => {
350
- const text = line.trim();
351
- if (!text || !text.startsWith("data:")) {
352
- return void 0;
353
- }
354
- const data = text.slice("data:".length).trim();
355
- if (!data || data === "[DONE]") {
356
- return void 0;
357
- }
358
- try {
359
- return parseExecStreamEvent(JSON.parse(data));
360
- } catch (error) {
361
- if (error instanceof SyntaxError) {
362
- throw new Error("Celesto returned malformed JSON in the command stream.");
363
- }
364
- throw error;
365
- }
366
- };
367
- var createManagedSignal = (signal, timeoutMs) => {
368
- if (!timeoutMs || timeoutMs <= 0) {
369
- return { signal, cleanup: () => {
370
- } };
371
- }
372
- const controller = new AbortController();
373
- const abort = () => controller.abort();
374
- if (signal?.aborted) {
375
- abort();
376
- } else {
377
- signal?.addEventListener("abort", abort, { once: true });
378
- }
379
- const timer = setTimeout(abort, timeoutMs);
380
- return {
381
- signal: controller.signal,
382
- cleanup: () => {
383
- clearTimeout(timer);
384
- signal?.removeEventListener("abort", abort);
385
- }
386
- };
387
- };
388
- var toNetworkError = (error) => {
389
- if (error instanceof CelestoNetworkError) return error;
390
- const cause = error instanceof Error ? error : new Error(String(error));
391
- return new CelestoNetworkError(cause.message, cause);
392
- };
393
- var withFallbackCommandId = (event, commandId) => {
394
- if (event.type !== "exit" || event.commandId || !commandId) return event;
395
- return { ...event, commandId };
396
- };
397
408
  var ComputersClient = class {
398
409
  constructor(config) {
399
410
  this.config = config;
400
411
  }
401
412
  async create(params = {}, options) {
402
413
  const ctx = buildRequestContext(this.config);
403
- 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 }, {
404
428
  method: "POST",
405
429
  path: computersPath(""),
406
430
  body: buildCreateComputerBody(params),
407
- ...pickOverrides(options)
431
+ headers,
432
+ signal: options?.signal
408
433
  });
409
434
  return toComputerInfo(data);
410
435
  }
@@ -445,100 +470,43 @@ var ComputersClient = class {
445
470
  return toComputerInfo(data);
446
471
  }
447
472
  async exec(computerId, command, params = {}, options) {
448
- const ctx = buildRequestContext(this.config);
449
- const managedSignal = createManagedSignal(
450
- params.signal ?? options?.signal,
451
- this.config.timeoutMs
452
- );
453
- try {
454
- const data = await request(ctx, {
455
- method: "POST",
456
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
457
- body: {
458
- command,
459
- timeout: params.timeout ?? 30
460
- },
461
- headers: options?.headers,
462
- signal: managedSignal.signal
463
- });
464
- return toExecResponse(data);
465
- } finally {
466
- 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.");
467
475
  }
468
- }
469
- async *execStream(computerId, command, params = {}, options) {
470
- const ctx = buildRequestContext(this.config);
471
- const managedSignal = createManagedSignal(
472
- params.signal ?? options?.signal,
473
- this.config.timeoutMs
474
- );
475
- let reader;
476
- let completed = false;
477
- try {
478
- const response = await requestStream(ctx, {
479
- method: "POST",
480
- path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
481
- body: {
482
- command,
483
- timeout: params.timeout ?? 30
484
- },
485
- headers: options?.headers,
486
- signal: managedSignal.signal
487
- });
488
- if (!response.body) {
489
- throw new Error("Celesto did not return a command output stream.");
490
- }
491
- const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
492
- reader = response.body.getReader();
493
- const decoder = new TextDecoder();
494
- let buffer = "";
495
- while (true) {
496
- let chunk;
497
- try {
498
- chunk = await reader.read();
499
- } catch (error) {
500
- throw toNetworkError(error);
501
- }
502
- if (chunk.done) {
503
- completed = true;
504
- buffer += decoder.decode();
505
- break;
506
- }
507
- buffer += decoder.decode(chunk.value, { stream: true });
508
- let newlineIndex = buffer.indexOf("\n");
509
- while (newlineIndex !== -1) {
510
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
511
- buffer = buffer.slice(newlineIndex + 1);
512
- const parsed = parseSseDataLine(line);
513
- if (parsed) {
514
- const event = withFallbackCommandId(parsed, responseCommandId);
515
- yield event;
516
- if (event.type === "exit") return;
517
- }
518
- 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.");
519
481
  }
520
482
  }
521
- if (buffer) {
522
- const parsed = parseSseDataLine(buffer);
523
- if (parsed) {
524
- const event = withFallbackCommandId(parsed, responseCommandId);
525
- yield event;
526
- if (event.type === "exit") return;
527
- }
528
- }
529
- throw new Error("Command stream ended before Celesto returned an exit status.");
530
- } finally {
531
- if (reader) {
532
- if (!completed) {
533
- try {
534
- await reader.cancel();
535
- } catch {
536
- }
537
- }
538
- reader.releaseLock();
539
- }
540
- managedSignal.cleanup();
541
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
+ };
542
510
  }
543
511
  async listCommandHistory(computerId, params = {}, options) {
544
512
  const ctx = buildRequestContext(this.config);
@@ -690,6 +658,9 @@ var Computer = class _Computer {
690
658
  get status() {
691
659
  return this.info.status;
692
660
  }
661
+ get sizeId() {
662
+ return this.info.sizeId;
663
+ }
693
664
  get vcpus() {
694
665
  return this.info.vcpus;
695
666
  }
@@ -744,7 +715,7 @@ var Computer = class _Computer {
744
715
  async exec(command, params = {}) {
745
716
  return this.run(command, params);
746
717
  }
747
- /** 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. */
748
719
  runStream(command, params = {}) {
749
720
  return this.client.execStream(this.id, command, params);
750
721
  }
@@ -815,9 +786,12 @@ var Computer = class _Computer {
815
786
  };
816
787
 
817
788
  export {
789
+ CelestoError,
790
+ CelestoApiError,
791
+ CelestoNetworkError,
818
792
  MISSING_CREDENTIALS_MESSAGE,
819
793
  resolveCelestoApiKey,
820
794
  resolveClientConfig,
821
795
  Computer
822
796
  };
823
- //# sourceMappingURL=chunk-B4JRBDUO.js.map
797
+ //# sourceMappingURL=chunk-3HEUI5UL.js.map