@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
package/dist/index.cjs CHANGED
@@ -30,41 +30,22 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- ALLOWED_CONFIG_KEYS: () => ALLOWED_CONFIG_KEYS,
34
- AgentArchivedError: () => AgentArchivedError,
35
- AgentsClient: () => AgentsClient,
36
- BudgetExceededError: () => BudgetExceededError,
37
33
  CelestoApiError: () => CelestoApiError,
38
34
  CelestoError: () => CelestoError,
39
35
  CelestoNetworkError: () => CelestoNetworkError,
40
36
  Computer: () => Computer,
41
- ConfigKeyNotAllowedError: () => ConfigKeyNotAllowedError,
42
- EVENTS_VERSION: () => EVENTS_VERSION,
43
- EndUsersClient: () => EndUsersClient,
44
- GatekeeperClient: () => GatekeeperClient,
45
- IdempotencyConflictError: () => IdempotencyConflictError,
46
- KNOWN_EVENTS: () => KNOWN_EVENTS,
47
37
  MISSING_CREDENTIALS_MESSAGE: () => MISSING_CREDENTIALS_MESSAGE,
48
- ManagedAgentError: () => ManagedAgentError,
49
- ManagedAgentsClient: () => ManagedAgentsClient,
50
- ModelRequiresOwnKeyError: () => ModelRequiresOwnKeyError,
51
- ProviderNotConnectedError: () => ProviderNotConnectedError,
52
- RunsClient: () => RunsClient,
53
- RuntimeSettingsClient: () => RuntimeSettingsClient,
54
- SessionAgentMismatchError: () => SessionAgentMismatchError,
55
- SessionBusyError: () => SessionBusyError,
56
- SessionEndUserMismatchError: () => SessionEndUserMismatchError,
57
- SessionsClient: () => SessionsClient,
58
- eventText: () => eventText,
59
- isTerminal: () => isTerminal,
60
- parseRunEvents: () => parseRunEvents,
61
- parseSseFrames: () => parseSseFrames,
62
38
  resolveCelestoApiKey: () => resolveCelestoApiKey,
63
- resolveClientConfig: () => resolveClientConfig,
64
- toRunEvent: () => toRunEvent
39
+ resolveClientConfig: () => resolveClientConfig
65
40
  });
66
41
  module.exports = __toCommonJS(src_exports);
67
42
 
43
+ // src/core/auth.ts
44
+ var import_promises = require("fs/promises");
45
+ var import_node_os = require("os");
46
+ var import_node_path = __toESM(require("path"), 1);
47
+ var import_dotenv = require("dotenv");
48
+
68
49
  // src/core/config.ts
69
50
  var DEFAULT_BASE_URL = "https://api.celesto.ai";
70
51
  var buildRequestContext = (config) => ({
@@ -101,6 +82,70 @@ var CelestoNetworkError = class extends CelestoError {
101
82
  this.cause = cause;
102
83
  }
103
84
  };
85
+ function toNetworkError(cause) {
86
+ if (cause instanceof CelestoNetworkError) return cause;
87
+ const error = cause instanceof Error ? cause : new Error(String(cause));
88
+ return new CelestoNetworkError(error.message, error);
89
+ }
90
+
91
+ // src/core/auth.ts
92
+ var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
93
+ function nonEmpty(value) {
94
+ const trimmed = value?.trim();
95
+ return trimmed ? trimmed : void 0;
96
+ }
97
+ async function readDotEnvApiKey(cwd, readDotEnv) {
98
+ try {
99
+ const contents = await readDotEnv(import_node_path.default.join(cwd, ".env"));
100
+ return nonEmpty((0, import_dotenv.parse)(contents).CELESTO_API_KEY);
101
+ } catch {
102
+ return void 0;
103
+ }
104
+ }
105
+ async function loadCliCredentials(home) {
106
+ try {
107
+ const saved = JSON.parse(await (0, import_promises.readFile)(import_node_path.default.join(home, ".celesto", "credentials"), "utf8"));
108
+ const token = typeof saved?.api_key === "string" ? nonEmpty(saved.api_key) : void 0;
109
+ if (!token) return void 0;
110
+ const url = new URL(nonEmpty(typeof saved.base_url === "string" ? saved.base_url : void 0) ?? DEFAULT_BASE_URL);
111
+ const local = url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
112
+ if (!local && url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return void 0;
113
+ return { token, baseUrl: url.origin };
114
+ } catch {
115
+ return void 0;
116
+ }
117
+ }
118
+ async function resolveCredentials(options) {
119
+ const env = options.env ?? process.env;
120
+ const environmentKey = nonEmpty(env.CELESTO_API_KEY);
121
+ if (environmentKey) return { token: environmentKey };
122
+ const dotEnvKey = await readDotEnvApiKey(
123
+ options.cwd ?? process.cwd(),
124
+ options.readDotEnv ?? ((filePath) => (0, import_promises.readFile)(filePath, "utf8"))
125
+ );
126
+ if (dotEnvKey) return { token: dotEnvKey };
127
+ if (options.loadSavedApiKey) {
128
+ const token = await options.loadSavedApiKey();
129
+ return token ? { token } : void 0;
130
+ }
131
+ return loadCliCredentials(options.homeDir ?? (0, import_node_os.homedir)());
132
+ }
133
+ async function resolveCelestoApiKey(options = {}) {
134
+ return (await resolveCredentials(options))?.token;
135
+ }
136
+ async function resolveClientConfig(config = {}, options = {}) {
137
+ if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
138
+ const credentials = await resolveCredentials(options);
139
+ if (!credentials) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
140
+ if (credentials.baseUrl && config.baseUrl !== void 0 && new URL(config.baseUrl).origin !== credentials.baseUrl) {
141
+ 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.");
142
+ }
143
+ const baseUrl = config.baseUrl ?? credentials.baseUrl;
144
+ return { ...config, token: credentials.token, ...baseUrl === void 0 ? {} : { baseUrl } };
145
+ }
146
+
147
+ // src/computers/client.ts
148
+ var import_node_crypto = require("crypto");
104
149
 
105
150
  // src/core/http.ts
106
151
  var joinUrl = (baseUrl, path2) => {
@@ -170,8 +215,7 @@ var buildRequestInit = (ctx, options) => {
170
215
  }
171
216
  const init = {
172
217
  method: options.method,
173
- headers,
174
- signal: options.signal
218
+ headers
175
219
  };
176
220
  if (options.body !== void 0) {
177
221
  headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
@@ -179,17 +223,30 @@ var buildRequestInit = (ctx, options) => {
179
223
  }
180
224
  return { url, init };
181
225
  };
226
+ function requestDeadline(signal, timeoutMs) {
227
+ if (!timeoutMs || timeoutMs <= 0 || signal?.aborted) return { signal, cleanup: () => {
228
+ } };
229
+ const controller = new AbortController();
230
+ const abort = () => controller.abort(signal?.reason);
231
+ signal?.addEventListener("abort", abort, { once: true });
232
+ const timer = setTimeout(
233
+ () => controller.abort(new DOMException("Celesto request timed out.", "TimeoutError")),
234
+ timeoutMs
235
+ );
236
+ return {
237
+ signal: controller.signal,
238
+ cleanup: () => {
239
+ clearTimeout(timer);
240
+ signal?.removeEventListener("abort", abort);
241
+ }
242
+ };
243
+ }
182
244
  var request = async (ctx, options) => {
183
245
  const { url, init } = buildRequestInit(ctx, options);
184
- let timeoutId;
185
- let controller;
186
- if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
187
- controller = new AbortController();
188
- timeoutId = setTimeout(() => controller?.abort(), ctx.timeoutMs);
189
- init.signal = controller.signal;
190
- }
246
+ const { signal, cleanup } = requestDeadline(options.signal, ctx.timeoutMs);
191
247
  try {
192
- const response = await ctx.fetch(url, init);
248
+ if (signal?.aborted) throw signal.reason;
249
+ const response = await ctx.fetch(url, { ...init, signal });
193
250
  const data = await parseResponseBody(response);
194
251
  if (!response.ok) {
195
252
  const message = extractErrorMessage(data, response.status);
@@ -206,259 +263,14 @@ var request = async (ctx, options) => {
206
263
  if (err instanceof CelestoApiError) {
207
264
  throw err;
208
265
  }
209
- const error = err instanceof Error ? err : new Error(String(err));
210
- throw new CelestoNetworkError(error.message, error);
266
+ throw toNetworkError(err);
211
267
  } finally {
212
- if (timeoutId) {
213
- clearTimeout(timeoutId);
214
- }
215
- }
216
- };
217
- var requestStream = async (ctx, options) => {
218
- const { url, init } = buildRequestInit(ctx, options);
219
- try {
220
- const response = await ctx.fetch(url, init);
221
- if (!response.ok) {
222
- const data = await parseResponseBody(response);
223
- const message = extractErrorMessage(data, response.status);
224
- throw new CelestoApiError(
225
- message,
226
- response.status,
227
- data,
228
- response.headers.get("x-request-id") ?? void 0,
229
- response.headers
230
- );
231
- }
232
- return response;
233
- } catch (err) {
234
- if (err instanceof CelestoApiError) {
235
- throw err;
236
- }
237
- const error = err instanceof Error ? err : new Error(String(err));
238
- throw new CelestoNetworkError(error.message, error);
268
+ cleanup();
239
269
  }
240
270
  };
241
271
 
242
- // src/gatekeeper/client.ts
243
- var toConnectRequest = (payload) => ({
244
- subject: payload.subject,
245
- provider: payload.provider ?? "google_drive",
246
- project_name: payload.projectName,
247
- redirect_uri: payload.redirectUri
248
- });
249
- var toConnectResponse = (payload) => ({
250
- status: payload.status,
251
- oauthUrl: payload.oauth_url ?? void 0,
252
- connectionId: payload.connection_id ?? void 0
253
- });
254
- var toConnection = (payload) => ({
255
- id: payload.id,
256
- subject: payload.subject,
257
- provider: payload.provider,
258
- projectId: payload.project_id,
259
- accountEmail: payload.account_email ?? null,
260
- scopes: payload.scopes ?? [],
261
- status: payload.status,
262
- createdAt: payload.created_at,
263
- updatedAt: payload.updated_at,
264
- lastUsedAt: payload.last_used_at ?? null,
265
- accessRules: payload.access_rules ? {
266
- version: payload.access_rules.version ?? "1",
267
- allowedFolders: payload.access_rules.allowed_folders ?? [],
268
- allowedFiles: payload.access_rules.allowed_files ?? [],
269
- unrestricted: false
270
- } : null
271
- });
272
- var toAccessRules = (payload) => ({
273
- version: payload.version,
274
- allowedFolders: payload.allowed_folders ?? [],
275
- allowedFiles: payload.allowed_files ?? [],
276
- unrestricted: payload.unrestricted
277
- });
278
- var toDriveFile = (payload) => ({
279
- id: payload.id,
280
- name: payload.name ?? null,
281
- mimeType: payload.mime_type ?? null,
282
- size: payload.size ?? null,
283
- modifiedTime: payload.modified_time ?? null,
284
- createdTime: payload.created_time ?? null,
285
- webViewLink: payload.web_view_link ?? null,
286
- iconLink: payload.icon_link ?? null,
287
- thumbnailLink: payload.thumbnail_link ?? null,
288
- parents: payload.parents ?? null,
289
- driveId: payload.drive_id ?? null,
290
- shared: payload.shared ?? null,
291
- ownedByMe: payload.owned_by_me ?? null
292
- });
293
- var gatekeeperPath = (path2) => `/v1/gatekeeper${path2}`;
294
- var pickOverrides = (options) => ({
295
- headers: options?.headers,
296
- signal: options?.signal
297
- });
298
- var GatekeeperClient = class {
299
- constructor(config) {
300
- this.config = config;
301
- }
302
- async connect(payload, options) {
303
- const ctx = buildRequestContext(this.config);
304
- const data = await request(ctx, {
305
- method: "POST",
306
- path: gatekeeperPath("/connect"),
307
- body: toConnectRequest(payload),
308
- ...pickOverrides(options)
309
- });
310
- return toConnectResponse(data);
311
- }
312
- async listConnections(params, options) {
313
- const ctx = buildRequestContext(this.config);
314
- const data = await request(ctx, {
315
- method: "GET",
316
- path: gatekeeperPath("/connections"),
317
- query: {
318
- project_name: params.projectName,
319
- status_filter: params.statusFilter
320
- },
321
- ...pickOverrides(options)
322
- });
323
- return {
324
- total: data.total,
325
- data: data.data.map(toConnection)
326
- };
327
- }
328
- async getConnection(connectionId, options) {
329
- const ctx = buildRequestContext(this.config);
330
- const data = await request(ctx, {
331
- method: "GET",
332
- path: gatekeeperPath(`/connections/${connectionId}`),
333
- ...pickOverrides(options)
334
- });
335
- return toConnection(data);
336
- }
337
- async revokeConnection(params, options) {
338
- const ctx = buildRequestContext(this.config);
339
- return request(ctx, {
340
- method: "DELETE",
341
- path: gatekeeperPath("/connections"),
342
- query: {
343
- subject: params.subject,
344
- project_name: params.projectName,
345
- provider: params.provider
346
- },
347
- ...pickOverrides(options)
348
- });
349
- }
350
- async listDriveFiles(params, options) {
351
- const ctx = buildRequestContext(this.config);
352
- const data = await request(ctx, {
353
- method: "GET",
354
- path: gatekeeperPath("/connectors/drive/files"),
355
- query: {
356
- project_name: params.projectName,
357
- subject: params.subject,
358
- page_size: params.pageSize,
359
- page_token: params.pageToken,
360
- folder_id: params.folderId,
361
- query: params.query,
362
- include_folders: params.includeFolders,
363
- order_by: params.orderBy
364
- },
365
- ...pickOverrides(options)
366
- });
367
- return {
368
- files: data.files.map(toDriveFile),
369
- nextPageToken: data.next_page_token ?? null
370
- };
371
- }
372
- async getAccessRules(connectionId, options) {
373
- const ctx = buildRequestContext(this.config);
374
- const data = await request(ctx, {
375
- method: "GET",
376
- path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
377
- ...pickOverrides(options)
378
- });
379
- return toAccessRules(data);
380
- }
381
- async updateAccessRules(params, options) {
382
- const ctx = buildRequestContext(this.config);
383
- const data = await request(ctx, {
384
- method: "PUT",
385
- path: gatekeeperPath("/connections/access-rules"),
386
- query: {
387
- subject: params.subject,
388
- project_name: params.projectName,
389
- provider: params.provider
390
- },
391
- body: {
392
- allowed_folders: params.accessRules.allowedFolders ?? [],
393
- allowed_files: params.accessRules.allowedFiles ?? []
394
- },
395
- ...pickOverrides(options)
396
- });
397
- return toAccessRules(data);
398
- }
399
- async clearAccessRules(connectionId, options) {
400
- const ctx = buildRequestContext(this.config);
401
- const data = await request(ctx, {
402
- method: "DELETE",
403
- path: gatekeeperPath(`/connections/${connectionId}/access-rules`),
404
- ...pickOverrides(options)
405
- });
406
- return toAccessRules(data);
407
- }
408
- };
409
-
410
- // src/core/auth.ts
411
- var import_node_child_process = require("child_process");
412
- var import_promises = require("fs/promises");
413
- var import_node_path = __toESM(require("path"), 1);
414
- var import_node_util = require("util");
415
- var import_dotenv = require("dotenv");
416
- var execFile = (0, import_node_util.promisify)(import_node_child_process.execFile);
417
- var MISSING_CREDENTIALS_MESSAGE = "No Celesto credentials found. Run pip install celesto && celesto auth login, or export CELESTO_API_KEY.";
418
- function nonEmpty(value) {
419
- const trimmed = value?.trim();
420
- return trimmed ? trimmed : void 0;
421
- }
422
- async function readDotEnvApiKey(cwd, readDotEnv) {
423
- try {
424
- const contents = await readDotEnv(import_node_path.default.join(cwd, ".env"));
425
- return nonEmpty((0, import_dotenv.parse)(contents).CELESTO_API_KEY);
426
- } catch {
427
- return void 0;
428
- }
429
- }
430
- async function loadCliApiKey() {
431
- try {
432
- const { stdout } = await execFile("celesto", ["auth", "token"], {
433
- encoding: "utf8",
434
- timeout: 5e3,
435
- maxBuffer: 64 * 1024
436
- });
437
- return nonEmpty(stdout);
438
- } catch {
439
- return void 0;
440
- }
441
- }
442
- async function resolveCelestoApiKey(options = {}) {
443
- const env = options.env ?? process.env;
444
- const environmentKey = nonEmpty(env.CELESTO_API_KEY);
445
- if (environmentKey) return environmentKey;
446
- const dotEnvKey = await readDotEnvApiKey(
447
- options.cwd ?? process.cwd(),
448
- options.readDotEnv ?? ((filePath) => (0, import_promises.readFile)(filePath, "utf8"))
449
- );
450
- if (dotEnvKey) return dotEnvKey;
451
- return (options.loadSavedApiKey ?? loadCliApiKey)();
452
- }
453
- async function resolveClientConfig(config = {}, options = {}) {
454
- if (nonEmpty(config.token) || nonEmpty(config.apiKey)) return config;
455
- const apiKey = await resolveCelestoApiKey(options);
456
- if (!apiKey) throw new CelestoError(MISSING_CREDENTIALS_MESSAGE);
457
- return { ...config, token: apiKey };
458
- }
459
-
460
272
  // src/computers/client.ts
461
- var toConnection2 = (payload) => {
273
+ var toConnection = (payload) => {
462
274
  if (!payload) {
463
275
  return void 0;
464
276
  }
@@ -483,6 +295,7 @@ var toComputerInfo = (payload) => ({
483
295
  id: payload.id,
484
296
  name: payload.name,
485
297
  status: payload.status,
298
+ ...payload.size_id === void 0 ? {} : { sizeId: payload.size_id },
486
299
  vcpus: payload.vcpus,
487
300
  ramMb: payload.ram_mb,
488
301
  diskSizeMb: payload.disk_size_mb,
@@ -491,7 +304,7 @@ var toComputerInfo = (payload) => ({
491
304
  templateVersion: payload.template_version ?? null,
492
305
  persistentHome: payload.external_volume_enabled ?? false,
493
306
  networkPolicy: payload.network_policy ?? { mode: "open" },
494
- connection: toConnection2(payload.connection),
307
+ connection: toConnection(payload.connection),
495
308
  publishedPorts: payload.published_ports?.map(toPublishedPortInfo),
496
309
  lastError: payload.last_error ?? null,
497
310
  createdAt: payload.created_at,
@@ -521,18 +334,50 @@ var toCommandHistoryEntry = (payload) => ({
521
334
  stderrBytes: payload.stderr_bytes,
522
335
  errorType: payload.error_type
523
336
  });
337
+ function authenticatedGatewayUrl(gatewayUrl, token) {
338
+ const separator = gatewayUrl.includes("?") ? "&" : "?";
339
+ return `${gatewayUrl}${separator}token=${encodeURIComponent(token)}`;
340
+ }
524
341
  var toTerminalConnectionInfo = (payload) => {
525
- const separator = payload.gateway_url.includes("?") ? "&" : "?";
526
342
  return {
527
343
  terminalId: payload.terminal_id,
528
344
  gatewayUrl: payload.gateway_url,
529
- url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
345
+ url: authenticatedGatewayUrl(payload.gateway_url, payload.token),
530
346
  token: payload.token,
531
347
  expiresAt: payload.expires_at,
532
348
  headers: {},
533
349
  firstMessage: ""
534
350
  };
535
351
  };
352
+ var toBrowserConnectionInfo = (payload) => {
353
+ if (typeof payload !== "object" || payload === null || typeof payload.gateway_url !== "string" || typeof payload.token !== "string" || typeof payload.expires_at !== "string") {
354
+ throw new CelestoError(
355
+ "Celesto did not return browser connection details. Call createBrowserConnection() again."
356
+ );
357
+ }
358
+ const connection = payload;
359
+ return {
360
+ gatewayUrl: connection.gateway_url,
361
+ url: authenticatedGatewayUrl(connection.gateway_url, connection.token),
362
+ token: connection.token,
363
+ expiresAt: connection.expires_at
364
+ };
365
+ };
366
+ var toDisplayConnectionInfo = (payload) => {
367
+ if (typeof payload !== "object" || payload === null || payload.mode !== "read_only" && payload.mode !== "read_write") {
368
+ throw new CelestoError(
369
+ "Celesto did not return display connection details. Call createDisplayConnection() again."
370
+ );
371
+ }
372
+ const connection = payload;
373
+ try {
374
+ return { ...toBrowserConnectionInfo(connection), mode: connection.mode };
375
+ } catch {
376
+ throw new CelestoError(
377
+ "Celesto did not return display connection details. Call createDisplayConnection() again."
378
+ );
379
+ }
380
+ };
536
381
  var toSandboxTemplateInfo = (payload) => ({
537
382
  id: payload.id,
538
383
  displayName: payload.display_name,
@@ -543,92 +388,36 @@ var toSandboxTemplateInfo = (payload) => ({
543
388
  version: payload.version ?? null,
544
389
  experimental: payload.experimental
545
390
  });
546
- var diskUnitsToMb = {
547
- "": 1,
548
- m: 1,
549
- mb: 1,
550
- mib: 1,
551
- g: 1024,
552
- gb: 1024,
553
- gib: 1024,
554
- t: 1024 * 1024,
555
- tb: 1024 * 1024,
556
- tib: 1024 * 1024
557
- };
558
- var isAsciiDigit = (char) => char >= "0" && char <= "9";
559
- var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
560
- var isSeparatorWhitespace = (char) => char === " " || char === " ";
561
- var parseDiskString = (disk) => {
562
- const value = disk.trim();
563
- if (!value) {
564
- return void 0;
565
- }
566
- let index = 0;
567
- let digitCount = 0;
568
- let hasDecimalPoint = false;
569
- while (index < value.length) {
570
- const char = value[index];
571
- if (isAsciiDigit(char)) {
572
- digitCount += 1;
573
- index += 1;
574
- continue;
391
+ var resourceOverrides = ["cpus", "vcpus", "memory", "ramMb", "disk", "diskSizeMb"];
392
+ var createOptions = /* @__PURE__ */ new Set([
393
+ "sizeId",
394
+ "idempotencyKey",
395
+ "networkPolicy",
396
+ "image",
397
+ "templateId",
398
+ "templateVersion",
399
+ "persistentHome",
400
+ ...resourceOverrides
401
+ ]);
402
+ var buildCreateComputerBody = (params) => {
403
+ for (const field of Object.keys(params)) {
404
+ if (field === "size" || field === "size_id") {
405
+ throw new TypeError(`${field} is not a Cloud computer create option. Use sizeId instead.`);
575
406
  }
576
- if (char === "." && !hasDecimalPoint) {
577
- hasDecimalPoint = true;
578
- index += 1;
579
- continue;
407
+ if (!createOptions.has(field)) {
408
+ throw new TypeError(`Unknown computer create option ${JSON.stringify(field)}. Remove it and retry.`);
580
409
  }
581
- break;
582
410
  }
583
- if (digitCount === 0 || value[index - 1] === ".") {
584
- return void 0;
585
- }
586
- const amount = value.slice(0, index);
587
- while (index < value.length && isSeparatorWhitespace(value[index])) {
588
- index += 1;
589
- }
590
- const unit = value.slice(index);
591
- if ([...unit].some((char) => !isAsciiLetter(char))) {
592
- return void 0;
411
+ if (resourceOverrides.some((field) => params[field] !== void 0)) {
412
+ throw new TypeError("Cloud computers do not accept CPU, memory, or disk overrides. Use sizeId instead.");
593
413
  }
594
- return { amount, unit };
595
- };
596
- var parseDiskSizeMb = (disk) => {
597
- if (disk === void 0) {
598
- return void 0;
599
- }
600
- if (typeof disk === "number") {
601
- if (!Number.isInteger(disk) || disk <= 0) {
602
- throw new Error("disk as a number must be a whole number of MB.");
414
+ const body = {};
415
+ if (params.sizeId !== void 0) {
416
+ if (typeof params.sizeId !== "string" || !params.sizeId.trim() || params.sizeId.length > 32) {
417
+ throw new TypeError('Choose a sizeId of 1\u201332 characters, such as "micro".');
603
418
  }
604
- return disk;
605
- }
606
- const parsedDisk = parseDiskString(disk);
607
- if (!parsedDisk) {
608
- throw new Error("disk must be a size in MB or a string like '2gb'.");
609
- }
610
- const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
611
- if (multiplier === void 0) {
612
- throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
613
- }
614
- const sizeMb = Number(parsedDisk.amount) * multiplier;
615
- if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
616
- throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
419
+ body.size_id = params.sizeId;
617
420
  }
618
- return sizeMb;
619
- };
620
- var buildCreateComputerBody = (params) => {
621
- if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
622
- throw new Error("cpus and vcpus must have the same value when both are provided.");
623
- }
624
- if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
625
- throw new Error("memory and ramMb must have the same value when both are provided.");
626
- }
627
- const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
628
- if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
629
- throw new Error("disk and diskSizeMb must have the same value when both are provided.");
630
- }
631
- const body = {};
632
421
  if (params.networkPolicy !== void 0) {
633
422
  const policy = params.networkPolicy;
634
423
  if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
@@ -639,18 +428,6 @@ var buildCreateComputerBody = (params) => {
639
428
  }
640
429
  body.network_policy = { mode: policy.mode };
641
430
  }
642
- const vcpus = params.vcpus ?? params.cpus;
643
- const ramMb = params.ramMb ?? params.memory;
644
- const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
645
- if (vcpus !== void 0) {
646
- body.vcpus = vcpus;
647
- }
648
- if (ramMb !== void 0) {
649
- body.ram_mb = ramMb;
650
- }
651
- if (diskSizeMb !== void 0) {
652
- body.disk_size_mb = diskSizeMb;
653
- }
654
431
  if (params.image !== void 0) {
655
432
  body.image = params.image;
656
433
  }
@@ -666,114 +443,35 @@ var buildCreateComputerBody = (params) => {
666
443
  return body;
667
444
  };
668
445
  var computersPath = (path2) => `/v1/computers${path2}`;
669
- var pickOverrides2 = (options) => ({
446
+ var pickOverrides = (options) => ({
670
447
  headers: options?.headers,
671
448
  signal: options?.signal
672
449
  });
673
- var optionalNumber = (value) => typeof value === "number" ? value : void 0;
674
- var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
675
- var parseExecStreamEvent = (value) => {
676
- if (!value || typeof value !== "object") {
677
- throw new Error("Celesto returned an invalid command stream event.");
678
- }
679
- const event = value;
680
- if (event.type === "stdout" || event.type === "stderr") {
681
- if (typeof event.data !== "string") {
682
- throw new Error("Celesto returned command output without text data.");
683
- }
684
- return { type: event.type, data: event.data };
685
- }
686
- if (event.type === "started") {
687
- if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
688
- throw new Error("Celesto returned an invalid command-start event.");
689
- }
690
- return {
691
- type: "started",
692
- commandId: event.command_id,
693
- startedAtUnixMs: event.started_at_unix_ms,
694
- timeoutSeconds: event.timeout_seconds
695
- };
696
- }
697
- if (event.type === "exit") {
698
- if (typeof event.exit_code !== "number") {
699
- throw new Error("Celesto returned an invalid command-exit event.");
700
- }
701
- const result = {
702
- type: "exit",
703
- exitCode: event.exit_code
704
- };
705
- if (typeof event.command_id === "string") result.commandId = event.command_id;
706
- const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
707
- const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
708
- const durationMs = optionalNumber(event.duration_ms);
709
- const timedOut = optionalBoolean(event.timed_out);
710
- if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
711
- if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
712
- if (durationMs !== void 0) result.durationMs = durationMs;
713
- if (timedOut !== void 0) result.timedOut = timedOut;
714
- return result;
715
- }
716
- throw new Error("Celesto returned an unknown command stream event.");
717
- };
718
- var parseSseDataLine = (line) => {
719
- const text = line.trim();
720
- if (!text || !text.startsWith("data:")) {
721
- return void 0;
722
- }
723
- const data = text.slice("data:".length).trim();
724
- if (!data || data === "[DONE]") {
725
- return void 0;
726
- }
727
- try {
728
- return parseExecStreamEvent(JSON.parse(data));
729
- } catch (error) {
730
- if (error instanceof SyntaxError) {
731
- throw new Error("Celesto returned malformed JSON in the command stream.");
732
- }
733
- throw error;
734
- }
735
- };
736
- var createManagedSignal = (signal, timeoutMs) => {
737
- if (!timeoutMs || timeoutMs <= 0) {
738
- return { signal, cleanup: () => {
739
- } };
740
- }
741
- const controller = new AbortController();
742
- const abort = () => controller.abort();
743
- if (signal?.aborted) {
744
- abort();
745
- } else {
746
- signal?.addEventListener("abort", abort, { once: true });
747
- }
748
- const timer = setTimeout(abort, timeoutMs);
749
- return {
750
- signal: controller.signal,
751
- cleanup: () => {
752
- clearTimeout(timer);
753
- signal?.removeEventListener("abort", abort);
754
- }
755
- };
756
- };
757
- var toNetworkError = (error) => {
758
- if (error instanceof CelestoNetworkError) return error;
759
- const cause = error instanceof Error ? error : new Error(String(error));
760
- return new CelestoNetworkError(cause.message, cause);
761
- };
762
- var withFallbackCommandId = (event, commandId) => {
763
- if (event.type !== "exit" || event.commandId || !commandId) return event;
764
- return { ...event, commandId };
765
- };
766
450
  var ComputersClient = class {
767
451
  constructor(config) {
768
452
  this.config = config;
769
453
  }
770
454
  async create(params = {}, options) {
771
455
  const ctx = buildRequestContext(this.config);
772
- const data = await request(ctx, {
456
+ const headers = {};
457
+ let suppliedKey;
458
+ for (const source of [ctx.headers, options?.headers]) {
459
+ for (const [name, value] of Object.entries(source ?? {})) {
460
+ if (name.toLowerCase() === "idempotency-key") suppliedKey = value;
461
+ else headers[name] = value;
462
+ }
463
+ }
464
+ const key = params.idempotencyKey ?? suppliedKey ?? (0, import_node_crypto.randomUUID)();
465
+ if (typeof key !== "string" || !key.trim()) {
466
+ throw new TypeError("idempotencyKey must not be empty. Omit it to generate a key.");
467
+ }
468
+ headers["Idempotency-Key"] = key;
469
+ const data = await request({ ...ctx, headers: void 0 }, {
773
470
  method: "POST",
774
471
  path: computersPath(""),
775
472
  body: buildCreateComputerBody(params),
776
- ...pickOverrides2(options)
473
+ headers,
474
+ signal: options?.signal
777
475
  });
778
476
  return toComputerInfo(data);
779
477
  }
@@ -782,7 +480,7 @@ var ComputersClient = class {
782
480
  const data = await request(ctx, {
783
481
  method: "GET",
784
482
  path: computersPath("/templates"),
785
- ...pickOverrides2(options)
483
+ ...pickOverrides(options)
786
484
  });
787
485
  return data.map(toSandboxTemplateInfo);
788
486
  }
@@ -797,7 +495,7 @@ var ComputersClient = class {
797
495
  project_id: params.projectId,
798
496
  limit: params.limit
799
497
  },
800
- ...pickOverrides2(options)
498
+ ...pickOverrides(options)
801
499
  });
802
500
  return {
803
501
  computers: data.computers.map(toComputerInfo),
@@ -809,105 +507,48 @@ var ComputersClient = class {
809
507
  const data = await request(ctx, {
810
508
  method: "GET",
811
509
  path: computersPath(`/${encodeURIComponent(computerId)}`),
812
- ...pickOverrides2(options)
510
+ ...pickOverrides(options)
813
511
  });
814
512
  return toComputerInfo(data);
815
513
  }
816
514
  async exec(computerId, command, params = {}, options) {
817
- const ctx = buildRequestContext(this.config);
818
- const managedSignal = createManagedSignal(
819
- params.signal ?? options?.signal,
820
- this.config.timeoutMs
821
- );
822
- try {
823
- const data = await request(ctx, {
824
- method: "POST",
825
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
826
- body: {
827
- command,
828
- timeout: params.timeout ?? 30
829
- },
830
- headers: options?.headers,
831
- signal: managedSignal.signal
832
- });
833
- return toExecResponse(data);
834
- } finally {
835
- managedSignal.cleanup();
836
- }
837
- }
838
- async *execStream(computerId, command, params = {}, options) {
839
- const ctx = buildRequestContext(this.config);
840
- const managedSignal = createManagedSignal(
841
- params.signal ?? options?.signal,
842
- this.config.timeoutMs
843
- );
844
- let reader;
845
- let completed = false;
846
- try {
847
- const response = await requestStream(ctx, {
848
- method: "POST",
849
- path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
850
- body: {
851
- command,
852
- timeout: params.timeout ?? 30
853
- },
854
- headers: options?.headers,
855
- signal: managedSignal.signal
856
- });
857
- if (!response.body) {
858
- throw new Error("Celesto did not return a command output stream.");
859
- }
860
- const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
861
- reader = response.body.getReader();
862
- const decoder = new TextDecoder();
863
- let buffer = "";
864
- while (true) {
865
- let chunk;
866
- try {
867
- chunk = await reader.read();
868
- } catch (error) {
869
- throw toNetworkError(error);
870
- }
871
- if (chunk.done) {
872
- completed = true;
873
- buffer += decoder.decode();
874
- break;
875
- }
876
- buffer += decoder.decode(chunk.value, { stream: true });
877
- let newlineIndex = buffer.indexOf("\n");
878
- while (newlineIndex !== -1) {
879
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
880
- buffer = buffer.slice(newlineIndex + 1);
881
- const parsed = parseSseDataLine(line);
882
- if (parsed) {
883
- const event = withFallbackCommandId(parsed, responseCommandId);
884
- yield event;
885
- if (event.type === "exit") return;
886
- }
887
- newlineIndex = buffer.indexOf("\n");
888
- }
889
- }
890
- if (buffer) {
891
- const parsed = parseSseDataLine(buffer);
892
- if (parsed) {
893
- const event = withFallbackCommandId(parsed, responseCommandId);
894
- yield event;
895
- if (event.type === "exit") return;
896
- }
897
- }
898
- throw new Error("Command stream ended before Celesto returned an exit status.");
899
- } finally {
900
- if (reader) {
901
- if (!completed) {
902
- try {
903
- await reader.cancel();
904
- } catch {
905
- }
515
+ if (typeof command !== "string" || command.length === 0) {
516
+ throw new TypeError("Provide a non-empty command to run on the Cloud computer.");
517
+ }
518
+ if (command.length > 1e4) {
519
+ let count = 0;
520
+ for (const _ of command) {
521
+ if (++count > 1e4) {
522
+ throw new TypeError("Cloud commands allow at most 10,000 characters. Shorten the command and retry.");
906
523
  }
907
- reader.releaseLock();
908
524
  }
909
- managedSignal.cleanup();
910
525
  }
526
+ const timeout = params.timeout ?? 30;
527
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 300) {
528
+ throw new TypeError("Choose a whole-number command timeout between 1 and 300 seconds.");
529
+ }
530
+ const ctx = buildRequestContext(this.config);
531
+ const data = await request(ctx, {
532
+ method: "POST",
533
+ path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
534
+ body: { command, timeout },
535
+ headers: options?.headers,
536
+ signal: params.signal ?? options?.signal
537
+ });
538
+ return toExecResponse(data);
539
+ }
540
+ /** Yield output and exit events after the command has finished. */
541
+ async *execStream(computerId, command, params = {}, options) {
542
+ const { stdout, stderr, exitCode, commandId, durationMs, timedOut } = await this.exec(computerId, command, params, options);
543
+ if (stdout) yield { type: "stdout", data: stdout };
544
+ if (stderr) yield { type: "stderr", data: stderr };
545
+ yield {
546
+ type: "exit",
547
+ exitCode,
548
+ ...commandId == null ? {} : { commandId },
549
+ ...durationMs == null ? {} : { durationMs },
550
+ ...timedOut == null ? {} : { timedOut }
551
+ };
911
552
  }
912
553
  async listCommandHistory(computerId, params = {}, options) {
913
554
  const ctx = buildRequestContext(this.config);
@@ -915,7 +556,7 @@ var ComputersClient = class {
915
556
  method: "GET",
916
557
  path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
917
558
  query: { limit: params.limit },
918
- ...pickOverrides2(options)
559
+ ...pickOverrides(options)
919
560
  });
920
561
  return {
921
562
  commands: data.commands.map(toCommandHistoryEntry),
@@ -927,7 +568,7 @@ var ComputersClient = class {
927
568
  const data = await request(ctx, {
928
569
  method: "POST",
929
570
  path: computersPath(`/${encodeURIComponent(computerId)}/stop`),
930
- ...pickOverrides2(options)
571
+ ...pickOverrides(options)
931
572
  });
932
573
  return toComputerInfo(data);
933
574
  }
@@ -936,7 +577,7 @@ var ComputersClient = class {
936
577
  const data = await request(ctx, {
937
578
  method: "POST",
938
579
  path: computersPath(`/${encodeURIComponent(computerId)}/start`),
939
- ...pickOverrides2(options)
580
+ ...pickOverrides(options)
940
581
  });
941
582
  return toComputerInfo(data);
942
583
  }
@@ -945,7 +586,7 @@ var ComputersClient = class {
945
586
  const data = await request(ctx, {
946
587
  method: "DELETE",
947
588
  path: computersPath(`/${encodeURIComponent(computerId)}`),
948
- ...pickOverrides2(options)
589
+ ...pickOverrides(options)
949
590
  });
950
591
  return toComputerInfo(data);
951
592
  }
@@ -955,7 +596,7 @@ var ComputersClient = class {
955
596
  method: "POST",
956
597
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
957
598
  body: { port },
958
- ...pickOverrides2(options)
599
+ ...pickOverrides(options)
959
600
  });
960
601
  return toPublishedPortInfo(data);
961
602
  }
@@ -964,7 +605,7 @@ var ComputersClient = class {
964
605
  const data = await request(ctx, {
965
606
  method: "GET",
966
607
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
967
- ...pickOverrides2(options)
608
+ ...pickOverrides(options)
968
609
  });
969
610
  return data.map(toPublishedPortInfo);
970
611
  }
@@ -973,7 +614,7 @@ var ComputersClient = class {
973
614
  const data = await request(ctx, {
974
615
  method: "DELETE",
975
616
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports/${port}`),
976
- ...pickOverrides2(options)
617
+ ...pickOverrides(options)
977
618
  });
978
619
  return toPublishedPortInfo(data);
979
620
  }
@@ -983,10 +624,31 @@ var ComputersClient = class {
983
624
  const data = await request(ctx, {
984
625
  method: "POST",
985
626
  path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
986
- ...pickOverrides2(options)
627
+ ...pickOverrides(options)
987
628
  });
988
629
  return toTerminalConnectionInfo(data);
989
630
  }
631
+ /** Create a short-lived CDP connection for browser automation. */
632
+ async createBrowserConnection(computerIdOrName, options) {
633
+ const ctx = buildRequestContext(this.config);
634
+ const data = await request(ctx, {
635
+ method: "POST",
636
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/browser`),
637
+ ...pickOverrides(options)
638
+ });
639
+ return toBrowserConnectionInfo(data);
640
+ }
641
+ /** Create a short-lived RFB connection to watch or control the graphical display. */
642
+ async createDisplayConnection(computerIdOrName, params = {}, options) {
643
+ const ctx = buildRequestContext(this.config);
644
+ const data = await request(ctx, {
645
+ method: "POST",
646
+ path: computersPath(`/${encodeURIComponent(computerIdOrName)}/display`),
647
+ body: params.mode === void 0 ? void 0 : { mode: params.mode },
648
+ ...pickOverrides(options)
649
+ });
650
+ return toDisplayConnectionInfo(data);
651
+ }
990
652
  /** @deprecated Use createTerminalSession(). */
991
653
  async getTerminalConnection(computerIdOrName, options) {
992
654
  return this.createTerminalSession(computerIdOrName, options);
@@ -1038,6 +700,9 @@ var Computer = class _Computer {
1038
700
  get status() {
1039
701
  return this.info.status;
1040
702
  }
703
+ get sizeId() {
704
+ return this.info.sizeId;
705
+ }
1041
706
  get vcpus() {
1042
707
  return this.info.vcpus;
1043
708
  }
@@ -1092,7 +757,7 @@ var Computer = class _Computer {
1092
757
  async exec(command, params = {}) {
1093
758
  return this.run(command, params);
1094
759
  }
1095
- /** Run a shell command and stream output and exit events as they arrive. */
760
+ /** Run a shell command and yield buffered output and exit events after it finishes. */
1096
761
  runStream(command, params = {}) {
1097
762
  return this.client.execStream(this.id, command, params);
1098
763
  }
@@ -1108,6 +773,14 @@ var Computer = class _Computer {
1108
773
  async createTerminalSession() {
1109
774
  return this.client.createTerminalSession(this.id);
1110
775
  }
776
+ /** Create a short-lived CDP connection for browser automation. */
777
+ async createBrowserConnection() {
778
+ return this.client.createBrowserConnection(this.id);
779
+ }
780
+ /** Create a short-lived RFB connection to watch or control the graphical display. */
781
+ async createDisplayConnection(params = {}) {
782
+ return this.client.createDisplayConnection(this.id, params);
783
+ }
1111
784
  /** @deprecated Use createTerminalSession(). */
1112
785
  async getTerminalConnection() {
1113
786
  return this.createTerminalSession();
@@ -1153,1008 +826,14 @@ var Computer = class _Computer {
1153
826
  return unpublished;
1154
827
  }
1155
828
  };
1156
-
1157
- // src/agents/errors.ts
1158
- var ManagedAgentError = class extends CelestoApiError {
1159
- constructor(message, status, data, options = {}) {
1160
- super(message, status, data, options.requestId, options.headers);
1161
- /** True when retrying the identical request can succeed. */
1162
- this.retryable = false;
1163
- this.name = "ManagedAgentError";
1164
- this.code = options.code;
1165
- this.retryAfter = options.retryAfter;
1166
- }
1167
- };
1168
- var BudgetExceededError = class extends ManagedAgentError {
1169
- constructor(...args) {
1170
- super(...args);
1171
- this.name = "BudgetExceededError";
1172
- }
1173
- };
1174
- var SessionBusyError = class extends ManagedAgentError {
1175
- constructor(...args) {
1176
- super(...args);
1177
- this.retryable = true;
1178
- this.name = "SessionBusyError";
1179
- }
1180
- };
1181
- var IdempotencyConflictError = class extends ManagedAgentError {
1182
- constructor(...args) {
1183
- super(...args);
1184
- this.name = "IdempotencyConflictError";
1185
- }
1186
- };
1187
- var AgentArchivedError = class extends ManagedAgentError {
1188
- constructor(...args) {
1189
- super(...args);
1190
- this.name = "AgentArchivedError";
1191
- }
1192
- };
1193
- var ProviderNotConnectedError = class extends ManagedAgentError {
1194
- constructor(...args) {
1195
- super(...args);
1196
- this.name = "ProviderNotConnectedError";
1197
- }
1198
- };
1199
- var SessionAgentMismatchError = class extends ManagedAgentError {
1200
- constructor(...args) {
1201
- super(...args);
1202
- this.name = "SessionAgentMismatchError";
1203
- }
1204
- };
1205
- var SessionEndUserMismatchError = class extends ManagedAgentError {
1206
- constructor(...args) {
1207
- super(...args);
1208
- this.name = "SessionEndUserMismatchError";
1209
- }
1210
- };
1211
- var ModelRequiresOwnKeyError = class extends ManagedAgentError {
1212
- constructor(...args) {
1213
- super(...args);
1214
- this.name = "ModelRequiresOwnKeyError";
1215
- }
1216
- };
1217
- var ConfigKeyNotAllowedError = class extends ManagedAgentError {
1218
- constructor(...args) {
1219
- super(...args);
1220
- this.name = "ConfigKeyNotAllowedError";
1221
- }
1222
- };
1223
- var ERROR_CLASSES = {
1224
- budget_exceeded: BudgetExceededError,
1225
- session_busy: SessionBusyError,
1226
- idempotency_conflict: IdempotencyConflictError,
1227
- agent_archived: AgentArchivedError,
1228
- provider_not_connected: ProviderNotConnectedError,
1229
- session_agent_mismatch: SessionAgentMismatchError,
1230
- session_end_user_mismatch: SessionEndUserMismatchError,
1231
- model_requires_own_key: ModelRequiresOwnKeyError,
1232
- config_key_not_allowed: ConfigKeyNotAllowedError
1233
- };
1234
- var STATUS_FALLBACK = {
1235
- 402: BudgetExceededError
1236
- };
1237
- var readErrorCode = (data) => {
1238
- if (!data || typeof data !== "object") return void 0;
1239
- const record = data;
1240
- const detail = record.detail;
1241
- const raw = detail && typeof detail === "object" ? detail.code : record.code;
1242
- if (typeof raw !== "string") return void 0;
1243
- return raw in ERROR_CLASSES ? raw : void 0;
1244
- };
1245
- var readMessage = (data, fallback) => {
1246
- if (data && typeof data === "object") {
1247
- const detail = data.detail;
1248
- if (detail && typeof detail === "object") {
1249
- const message = detail.message;
1250
- if (typeof message === "string") return message;
1251
- }
1252
- }
1253
- return fallback;
1254
- };
1255
- var readRetryAfter = (headers) => {
1256
- const raw = headers?.get("retry-after");
1257
- if (!raw) return void 0;
1258
- const seconds = Number(raw);
1259
- return Number.isFinite(seconds) ? seconds : void 0;
1260
- };
1261
- var toManagedAgentError = (error) => {
1262
- if (!(error instanceof CelestoApiError) || error instanceof ManagedAgentError) {
1263
- return error;
1264
- }
1265
- const code = readErrorCode(error.data);
1266
- const ErrorClass = (code && ERROR_CLASSES[code]) ?? STATUS_FALLBACK[error.status];
1267
- if (!ErrorClass) return error;
1268
- return new ErrorClass(readMessage(error.data, error.message), error.status, error.data, {
1269
- code: code ?? (error.status === 402 ? "budget_exceeded" : void 0),
1270
- retryAfter: readRetryAfter(error.headers),
1271
- requestId: error.requestId,
1272
- headers: error.headers
1273
- });
1274
- };
1275
-
1276
- // src/agents/events.ts
1277
- var EVENTS_VERSION = "1";
1278
- var KNOWN_EVENTS = [
1279
- "run.started",
1280
- "message.delta",
1281
- "message.completed",
1282
- "tool.call",
1283
- "tool.result",
1284
- "usage",
1285
- "run.completed",
1286
- "run.failed"
1287
- ];
1288
- var KNOWN_EVENT_SET = new Set(KNOWN_EVENTS);
1289
- var asRecord = (value) => value && typeof value === "object" ? value : {};
1290
- var str = (value) => typeof value === "string" ? value : null;
1291
- var num = (value) => typeof value === "number" ? value : null;
1292
- var int = (value) => typeof value === "number" ? value : 0;
1293
- var money = (value) => typeof value === "string" ? value : "0.000000";
1294
- var toUsage = (value) => {
1295
- const raw = asRecord(value);
1296
- return {
1297
- inputTokens: int(raw.input_tokens),
1298
- outputTokens: int(raw.output_tokens),
1299
- totalTokens: int(raw.total_tokens),
1300
- costUsd: money(raw.cost_usd)
1301
- };
1302
- };
1303
- var toToolResultData = (raw) => {
1304
- const data = {
1305
- callId: str(raw.call_id),
1306
- name: str(raw.name),
1307
- turn: num(raw.turn)
1308
- };
1309
- if ("error" in raw) {
1310
- data.error = raw.error;
1311
- } else {
1312
- data.result = raw.result;
1313
- }
1314
- return data;
1315
- };
1316
- var toRunEvent = (frame) => {
1317
- const name = frame.event;
1318
- if (!name || !KNOWN_EVENT_SET.has(name)) return void 0;
1319
- let parsed;
1320
- try {
1321
- parsed = frame.data ? JSON.parse(frame.data) : {};
1322
- } catch {
1323
- return void 0;
1324
- }
1325
- const raw = asRecord(parsed);
1326
- const seq = frame.id !== void 0 && frame.id !== "" ? Number(frame.id) : NaN;
1327
- const position = Number.isFinite(seq) ? seq : null;
1328
- switch (name) {
1329
- case "run.started":
1330
- return {
1331
- name: "run.started",
1332
- seq: position,
1333
- data: {
1334
- runId: str(raw.run_id) ?? "",
1335
- agentId: str(raw.agent_id) ?? "",
1336
- agentVersionId: str(raw.agent_version_id) ?? "",
1337
- sessionId: str(raw.session_id) ?? "",
1338
- endUserId: str(raw.end_user_id) ?? "",
1339
- model: str(raw.model) ?? "",
1340
- createdAt: str(raw.created_at) ?? ""
1341
- }
1342
- };
1343
- case "message.delta":
1344
- return {
1345
- name: "message.delta",
1346
- seq: position,
1347
- data: { text: str(raw.text), turn: num(raw.turn) }
1348
- };
1349
- case "message.completed":
1350
- return {
1351
- name: "message.completed",
1352
- seq: position,
1353
- data: { text: str(raw.text), turn: num(raw.turn) }
1354
- };
1355
- case "tool.call":
1356
- return {
1357
- name: "tool.call",
1358
- seq: position,
1359
- data: {
1360
- callId: str(raw.call_id),
1361
- name: str(raw.name),
1362
- args: raw.args,
1363
- turn: num(raw.turn)
1364
- }
1365
- };
1366
- case "tool.result":
1367
- return { name: "tool.result", seq: position, data: toToolResultData(raw) };
1368
- case "usage":
1369
- return {
1370
- name: "usage",
1371
- seq: position,
1372
- data: {
1373
- turn: num(raw.turn),
1374
- model: str(raw.model),
1375
- inputTokens: int(raw.input_tokens),
1376
- outputTokens: int(raw.output_tokens),
1377
- totalTokens: int(raw.total_tokens),
1378
- costUsd: money(raw.cost_usd)
1379
- }
1380
- };
1381
- case "run.completed":
1382
- return {
1383
- name: "run.completed",
1384
- seq: position,
1385
- data: {
1386
- runId: str(raw.run_id) ?? "",
1387
- status: str(raw.status) ?? "completed",
1388
- output: str(raw.output),
1389
- turnCount: num(raw.turn_count),
1390
- usage: toUsage(raw.usage)
1391
- }
1392
- };
1393
- case "run.failed":
1394
- return {
1395
- name: "run.failed",
1396
- seq: position,
1397
- data: {
1398
- runId: str(raw.run_id) ?? "",
1399
- status: str(raw.status) ?? "failed",
1400
- errorCode: str(raw.error_code),
1401
- error: str(raw.error),
1402
- turnCount: num(raw.turn_count),
1403
- usage: toUsage(raw.usage)
1404
- }
1405
- };
1406
- default:
1407
- return void 0;
1408
- }
1409
- };
1410
- var isTerminal = (event) => event.name === "run.completed" || event.name === "run.failed";
1411
- var eventText = (event) => {
1412
- switch (event.name) {
1413
- case "message.delta":
1414
- case "message.completed":
1415
- return event.data.text ?? "";
1416
- case "run.completed":
1417
- return event.data.output ?? "";
1418
- default:
1419
- return "";
1420
- }
1421
- };
1422
- var SseDecoder = class {
1423
- constructor() {
1424
- this.buffer = "";
1425
- }
1426
- push(chunk) {
1427
- this.buffer += chunk;
1428
- const frames = [];
1429
- let boundary = this.findBoundary();
1430
- while (boundary) {
1431
- const block = this.buffer.slice(0, boundary.index);
1432
- this.buffer = this.buffer.slice(boundary.index + boundary.length);
1433
- const frame = parseFrame(block);
1434
- if (frame) frames.push(frame);
1435
- boundary = this.findBoundary();
1436
- }
1437
- return frames;
1438
- }
1439
- /** Anything left in the buffer when the stream ends. */
1440
- flush() {
1441
- const block = this.buffer;
1442
- this.buffer = "";
1443
- const frame = parseFrame(block);
1444
- return frame ? [frame] : [];
1445
- }
1446
- findBoundary() {
1447
- const lf = this.buffer.indexOf("\n\n");
1448
- const crlf = this.buffer.indexOf("\r\n\r\n");
1449
- if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
1450
- if (lf !== -1) return { index: lf, length: 2 };
1451
- return void 0;
1452
- }
1453
- };
1454
- var parseFrame = (block) => {
1455
- let event;
1456
- let id;
1457
- const dataLines = [];
1458
- let sawField = false;
1459
- for (const rawLine of block.split("\n")) {
1460
- const line = rawLine.replace(/\r$/, "");
1461
- if (line === "" || line.startsWith(":")) continue;
1462
- const separator = line.indexOf(":");
1463
- const field = separator === -1 ? line : line.slice(0, separator);
1464
- let value = separator === -1 ? "" : line.slice(separator + 1);
1465
- if (value.startsWith(" ")) value = value.slice(1);
1466
- if (field === "event") {
1467
- event = value;
1468
- sawField = true;
1469
- } else if (field === "data") {
1470
- dataLines.push(value);
1471
- sawField = true;
1472
- } else if (field === "id") {
1473
- id = value;
1474
- sawField = true;
1475
- }
1476
- }
1477
- if (!sawField) return void 0;
1478
- const frame = { data: dataLines.join("\n") };
1479
- if (event !== void 0) frame.event = event;
1480
- if (id !== void 0) frame.id = id;
1481
- return frame;
1482
- };
1483
- var parseSseFrames = (body) => {
1484
- const decoder = new SseDecoder();
1485
- return [...decoder.push(body), ...decoder.flush()];
1486
- };
1487
- var parseRunEvents = (body) => {
1488
- const events = [];
1489
- for (const frame of parseSseFrames(body)) {
1490
- const event = toRunEvent(frame);
1491
- if (event) events.push(event);
1492
- }
1493
- return events;
1494
- };
1495
-
1496
- // src/agents/client.ts
1497
- var runtimePath = (path2) => `/v1${path2}`;
1498
- var pickOverrides3 = (options) => ({
1499
- headers: options?.headers,
1500
- signal: options?.signal
1501
- });
1502
- var DEFAULT_RETRY_BACKOFF_MS = 1e3;
1503
- var CONFIG_KEYS = {
1504
- temperature: "temperature",
1505
- topP: "top_p",
1506
- maxTokens: "max_tokens",
1507
- maxOutputTokens: "max_output_tokens",
1508
- frequencyPenalty: "frequency_penalty",
1509
- presencePenalty: "presence_penalty",
1510
- seed: "seed",
1511
- stop: "stop",
1512
- reasoningEffort: "reasoning_effort",
1513
- verbosity: "verbosity",
1514
- maxTurns: "max_turns"
1515
- };
1516
- var ALLOWED_CONFIG_KEYS = Object.keys(CONFIG_KEYS);
1517
- var WIRE_TO_CONFIG_KEY = new Map(
1518
- Object.entries(CONFIG_KEYS).map(([key, wire]) => [
1519
- wire,
1520
- key
1521
- ])
1522
- );
1523
- var toConfigWire = (config) => {
1524
- if (!config) return void 0;
1525
- const wire = {};
1526
- const unknown = [];
1527
- for (const [key, value] of Object.entries(config)) {
1528
- if (value === void 0) continue;
1529
- const wireKey = CONFIG_KEYS[key];
1530
- if (!wireKey) {
1531
- unknown.push(key);
1532
- continue;
1533
- }
1534
- wire[wireKey] = value;
1535
- }
1536
- if (unknown.length > 0) {
1537
- throw new ConfigKeyNotAllowedError(
1538
- `Agent config does not accept ${unknown.join(", ")}. It accepts only: ${ALLOWED_CONFIG_KEYS.join(", ")}.`,
1539
- 422,
1540
- void 0,
1541
- { code: "config_key_not_allowed" }
1542
- );
1543
- }
1544
- return wire;
1545
- };
1546
- var toConfig = (wire) => {
1547
- if (!wire || typeof wire !== "object") return null;
1548
- const config = {};
1549
- for (const [wireKey, value] of Object.entries(wire)) {
1550
- const key = WIRE_TO_CONFIG_KEY.get(wireKey);
1551
- config[key ?? wireKey] = value;
1552
- }
1553
- return config;
1554
- };
1555
- var toAgent = (wire) => ({
1556
- id: wire.id,
1557
- object: wire.object ?? "agent",
1558
- name: wire.name,
1559
- description: wire.description ?? null,
1560
- model: wire.model,
1561
- instructions: wire.instructions ?? null,
1562
- config: toConfig(wire.config),
1563
- version: wire.version,
1564
- currentVersionId: wire.current_version_id,
1565
- projectId: wire.project_id,
1566
- organizationId: wire.organization_id,
1567
- status: wire.status,
1568
- createdAt: wire.created_at,
1569
- updatedAt: wire.updated_at
1570
- });
1571
- var toAgentVersion = (wire) => ({
1572
- id: wire.id,
1573
- object: wire.object ?? "agent_version",
1574
- agentId: wire.agent_id,
1575
- version: wire.version,
1576
- name: wire.name,
1577
- description: wire.description ?? null,
1578
- model: wire.model,
1579
- instructions: wire.instructions ?? null,
1580
- config: toConfig(wire.config),
1581
- createdAt: wire.created_at
1582
- });
1583
- var toUsage2 = (wire) => ({
1584
- inputTokens: wire.input_tokens,
1585
- outputTokens: wire.output_tokens,
1586
- totalTokens: wire.total_tokens,
1587
- // Money stays a string. Never parseFloat this.
1588
- costUsd: wire.cost_usd
1589
- });
1590
- var toRun = (wire) => ({
1591
- runId: wire.run_id,
1592
- object: wire.object ?? "run",
1593
- status: wire.status,
1594
- errorCode: wire.error_code ?? null,
1595
- error: wire.error ?? null,
1596
- output: wire.output ?? null,
1597
- usage: toUsage2(wire.usage),
1598
- agentId: wire.agent_id,
1599
- agentVersionId: wire.agent_version_id,
1600
- sessionId: wire.session_id,
1601
- endUserId: wire.end_user_id,
1602
- turnCount: wire.turn_count ?? null,
1603
- createdAt: wire.created_at,
1604
- startedAt: wire.started_at ?? null,
1605
- endedAt: wire.ended_at ?? null
1606
- });
1607
- var toSession = (wire) => ({
1608
- id: wire.id,
1609
- object: wire.object ?? "session",
1610
- agentId: wire.agent_id ?? null,
1611
- endUserId: wire.end_user_id,
1612
- status: wire.status,
1613
- messageCount: wire.message_count,
1614
- lastMessageAt: wire.last_message_at ?? null,
1615
- createdAt: wire.created_at
1616
- });
1617
- var toSessionMessage = (wire) => ({
1618
- seq: wire.seq,
1619
- role: wire.role ?? null,
1620
- item: wire.item,
1621
- createdAt: wire.created_at
1622
- });
1623
- var toBudget = (wire) => ({
1624
- capUsd: wire.cap_usd ?? null,
1625
- source: wire.source,
1626
- windowStart: wire.window_start,
1627
- windowResetsAt: wire.window_resets_at,
1628
- spentUsd: wire.spent_usd,
1629
- remainingUsd: wire.remaining_usd ?? null
1630
- });
1631
- var toEndUser = (wire) => ({
1632
- endUserId: wire.end_user_id,
1633
- object: wire.object ?? "end_user",
1634
- firstActivityAt: wire.first_activity_at,
1635
- budget: toBudget(wire.budget),
1636
- metadata: wire.metadata ?? null,
1637
- createdAt: wire.created_at
1638
- });
1639
- var toRuntimeSettings = (wire) => ({
1640
- organizationId: wire.organization_id,
1641
- defaultEndUserBudgetUsd: wire.default_end_user_budget_usd ?? null
1642
- });
1643
- var toPage = (wire, map) => ({
1644
- data: (wire.data ?? []).map(map),
1645
- hasMore: wire.has_more ?? false
1646
- });
1647
- var MONEY_PATTERN = /^\d{1,8}(\.\d{1,6})?$/;
1648
- var toMoneyString = (value) => {
1649
- if (typeof value === "number") {
1650
- throw new TypeError(
1651
- `Budget amounts cannot be a number (${value}): a JavaScript number cannot hold these amounts exactly. Pass a decimal string instead \u2014 "5.00", not 5.0.`
1652
- );
1653
- }
1654
- const text = value.trim();
1655
- if (!MONEY_PATTERN.test(text)) {
1656
- throw new TypeError(
1657
- `"${value}" is not a valid amount. Use a plain decimal amount with at most 8 digits before the point and 6 after, like "5.00" \u2014 no sign, no exponent, no currency symbol.`
1658
- );
1659
- }
1660
- return text;
1661
- };
1662
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1663
- var newIdempotencyKey = () => {
1664
- const uuid = globalThis.crypto?.randomUUID?.();
1665
- return uuid ?? `idem_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1666
- };
1667
- var BaseClient = class {
1668
- constructor(config) {
1669
- this.config = config;
1670
- }
1671
- /** Every call goes through here, so refusals arrive already typed. */
1672
- async call(options) {
1673
- try {
1674
- return await request(buildRequestContext(this.config), options);
1675
- } catch (error) {
1676
- throw toManagedAgentError(error);
1677
- }
1678
- }
1679
- };
1680
- var AgentsClient = class extends BaseClient {
1681
- /** Create an agent, at version 1. */
1682
- async create(params, options) {
1683
- const wire = await this.call({
1684
- method: "POST",
1685
- path: runtimePath("/agents"),
1686
- body: {
1687
- name: params.name,
1688
- model: params.model,
1689
- instructions: params.instructions,
1690
- description: params.description,
1691
- config: toConfigWire(params.config),
1692
- project_id: params.projectId
1693
- },
1694
- ...pickOverrides3(options)
1695
- });
1696
- return toAgent(wire);
1697
- }
1698
- /** List one page of agents. Check `hasMore`; there is no total count. */
1699
- async list(params = {}, options) {
1700
- const wire = await this.call({
1701
- method: "GET",
1702
- path: runtimePath("/agents"),
1703
- query: {
1704
- project_id: params.projectId,
1705
- include_archived: params.includeArchived,
1706
- limit: params.limit,
1707
- offset: params.offset
1708
- },
1709
- ...pickOverrides3(options)
1710
- });
1711
- return toPage(wire, toAgent);
1712
- }
1713
- /** Yield every agent, fetching pages as you go. */
1714
- async *listAll(params = {}, options) {
1715
- const pageSize = params.limit ?? 50;
1716
- let offset = 0;
1717
- for (; ; ) {
1718
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
1719
- yield* page.data;
1720
- if (page.data.length === 0 || !page.hasMore) return;
1721
- offset += page.data.length;
1722
- }
1723
- }
1724
- /** Get an agent, at its current version. */
1725
- async get(agentId, options) {
1726
- const wire = await this.call({
1727
- method: "GET",
1728
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1729
- ...pickOverrides3(options)
1730
- });
1731
- return toAgent(wire);
1732
- }
1733
- /**
1734
- * Replace an agent's definition, which cuts a new version.
1735
- *
1736
- * This is a full replacement, not a patch: whatever you leave out is
1737
- * cleared. Read the agent first if you only mean to change one field.
1738
- */
1739
- async update(agentId, params, options) {
1740
- const wire = await this.call({
1741
- method: "PUT",
1742
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1743
- body: {
1744
- name: params.name,
1745
- model: params.model,
1746
- instructions: params.instructions,
1747
- description: params.description,
1748
- config: toConfigWire(params.config)
1749
- },
1750
- ...pickOverrides3(options)
1751
- });
1752
- return toAgent(wire);
1753
- }
1754
- /**
1755
- * Archive an agent. Archived agents refuse new runs.
1756
- *
1757
- * Past runs, versions, and transcripts stay readable.
1758
- */
1759
- async archive(agentId, options) {
1760
- const wire = await this.call({
1761
- method: "DELETE",
1762
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1763
- ...pickOverrides3(options)
1764
- });
1765
- return { id: wire.id, status: wire.status };
1766
- }
1767
- /** List one page of an agent's versions. */
1768
- async listVersions(agentId, params = {}, options) {
1769
- const wire = await this.call({
1770
- method: "GET",
1771
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions`),
1772
- query: { limit: params.limit, offset: params.offset },
1773
- ...pickOverrides3(options)
1774
- });
1775
- return toPage(wire, toAgentVersion);
1776
- }
1777
- /** Yield every version of an agent, fetching pages as you go. */
1778
- async *listAllVersions(agentId, params = {}, options) {
1779
- const pageSize = params.limit ?? 50;
1780
- let offset = 0;
1781
- for (; ; ) {
1782
- const page = await this.listVersions(agentId, { limit: pageSize, offset }, options);
1783
- yield* page.data;
1784
- if (page.data.length === 0 || !page.hasMore) return;
1785
- offset += page.data.length;
1786
- }
1787
- }
1788
- /** Get one version of an agent by its number. */
1789
- async getVersion(agentId, versionNumber, options) {
1790
- const wire = await this.call({
1791
- method: "GET",
1792
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}`),
1793
- ...pickOverrides3(options)
1794
- });
1795
- return toAgentVersion(wire);
1796
- }
1797
- /**
1798
- * Roll back to an earlier version.
1799
- *
1800
- * This moves the agent's pointer; it does not cut a new version and nothing
1801
- * is lost.
1802
- */
1803
- async activateVersion(agentId, versionNumber, options) {
1804
- const wire = await this.call({
1805
- method: "POST",
1806
- path: runtimePath(
1807
- `/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}/activate`
1808
- ),
1809
- ...pickOverrides3(options)
1810
- });
1811
- return toAgent(wire);
1812
- }
1813
- };
1814
- var RunsClient = class extends BaseClient {
1815
- runBody(params, stream) {
1816
- return {
1817
- input: params.input,
1818
- end_user_id: params.endUserId,
1819
- session_id: params.sessionId,
1820
- max_turns: params.maxTurns,
1821
- stream
1822
- };
1823
- }
1824
- /** Retrying without a key can charge twice, so make one when retrying. */
1825
- idempotencyKey(params) {
1826
- if (params.idempotencyKey) return params.idempotencyKey;
1827
- return (params.maxRetries ?? 0) > 0 ? newIdempotencyKey() : void 0;
1828
- }
1829
- /**
1830
- * Run an agent and wait for the answer.
1831
- *
1832
- * @throws {@link BudgetExceededError} when the end user has spent their budget.
1833
- * @throws {@link SessionBusyError} when another run holds the session.
1834
- */
1835
- async create(agentId, params, options) {
1836
- const key = this.idempotencyKey(params);
1837
- const maxRetries = params.maxRetries ?? 0;
1838
- const headers = {
1839
- ...options?.headers ?? {},
1840
- ...key ? { "Idempotency-Key": key } : {}
1841
- };
1842
- for (let attempt = 0; ; attempt += 1) {
1843
- try {
1844
- const wire = await this.call({
1845
- method: "POST",
1846
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
1847
- body: this.runBody(params, false),
1848
- headers,
1849
- signal: options?.signal
1850
- });
1851
- return toRun(wire);
1852
- } catch (error) {
1853
- if (!(error instanceof SessionBusyError) || attempt >= maxRetries) throw error;
1854
- await sleep(
1855
- error.retryAfter !== void 0 ? error.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
1856
- );
1857
- }
1858
- }
1859
- }
1860
- /**
1861
- * Run an agent and watch it work.
1862
- *
1863
- * Yields events as the run happens: text as it is generated, each tool call
1864
- * and its result, what each generation cost, and finally `run.completed` or
1865
- * `run.failed`. Event names this SDK does not know are ignored, so a newer
1866
- * server cannot break an older client.
1867
- *
1868
- * A failed run arrives as a `run.failed` event, not a thrown error —
1869
- * including a run stopped mid-stream because the end user ran out of
1870
- * budget. Errors are thrown for runs that never started.
1871
- *
1872
- * A replay of an idempotency key omits `message.delta`: partial text is
1873
- * never stored, so there is nothing to replay.
1874
- *
1875
- * @example
1876
- * ```ts
1877
- * for await (const event of celesto.runs.stream(agent.id, {
1878
- * input: "Where is my order?",
1879
- * endUserId: "usr_8837",
1880
- * })) {
1881
- * if (event.name === "message.delta") process.stdout.write(event.data.text ?? "");
1882
- * }
1883
- * ```
1884
- */
1885
- async *stream(agentId, params, options) {
1886
- const key = this.idempotencyKey(params);
1887
- const maxRetries = params.maxRetries ?? 0;
1888
- const headers = {
1889
- Accept: "text/event-stream",
1890
- ...options?.headers ?? {},
1891
- ...key ? { "Idempotency-Key": key } : {}
1892
- };
1893
- for (let attempt = 0; ; attempt += 1) {
1894
- let response;
1895
- try {
1896
- response = await requestStream(buildRequestContext(this.config), {
1897
- method: "POST",
1898
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
1899
- body: this.runBody(params, true),
1900
- headers,
1901
- signal: options?.signal
1902
- });
1903
- } catch (error) {
1904
- const typed = toManagedAgentError(error);
1905
- if (!(typed instanceof SessionBusyError) || attempt >= maxRetries) throw typed;
1906
- await sleep(
1907
- typed.retryAfter !== void 0 ? typed.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
1908
- );
1909
- continue;
1910
- }
1911
- yield* readEventStream(response);
1912
- return;
1913
- }
1914
- }
1915
- /** Get a run by id, settled or not. */
1916
- async get(runId, options) {
1917
- const wire = await this.call({
1918
- method: "GET",
1919
- path: runtimePath(`/runs/${encodeURIComponent(runId)}`),
1920
- ...pickOverrides3(options)
1921
- });
1922
- return toRun(wire);
1923
- }
1924
- /**
1925
- * Read one page of a run's stored events.
1926
- *
1927
- * The same event contract as {@link stream}, read back after the fact,
1928
- * minus `message.delta` — partial text is never stored.
1929
- */
1930
- async listEvents(runId, params = {}, options) {
1931
- const wire = await this.call({
1932
- method: "GET",
1933
- path: runtimePath(`/runs/${encodeURIComponent(runId)}/events`),
1934
- query: { after_seq: params.afterSeq, limit: params.limit },
1935
- ...pickOverrides3(options)
1936
- });
1937
- return { data: wire.data ?? [], eventsVersion: wire.events_version };
1938
- }
1939
- /** Yield every stored event of a run, in order, fetching pages as you go. */
1940
- async *listAllEvents(runId, params = {}, options) {
1941
- const pageSize = params.limit ?? 100;
1942
- let afterSeq = params.afterSeq ?? 0;
1943
- for (; ; ) {
1944
- const page = await this.listEvents(runId, { afterSeq, limit: pageSize }, options);
1945
- yield* page.data;
1946
- if (page.data.length < pageSize) return;
1947
- const last = page.data[page.data.length - 1];
1948
- if (!last) return;
1949
- afterSeq = last.seq;
1950
- }
1951
- }
1952
- };
1953
- var SessionsClient = class extends BaseClient {
1954
- /** List one page of an end user's sessions. */
1955
- async list(params, options) {
1956
- const wire = await this.call({
1957
- method: "GET",
1958
- path: runtimePath("/sessions"),
1959
- query: {
1960
- end_user_id: params.endUserId,
1961
- limit: params.limit,
1962
- offset: params.offset
1963
- },
1964
- ...pickOverrides3(options)
1965
- });
1966
- return toPage(wire, toSession);
1967
- }
1968
- /** Yield every session for an end user, fetching pages as you go. */
1969
- async *listAll(params, options) {
1970
- const pageSize = params.limit ?? 50;
1971
- let offset = 0;
1972
- for (; ; ) {
1973
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
1974
- yield* page.data;
1975
- if (page.data.length === 0 || !page.hasMore) return;
1976
- offset += page.data.length;
1977
- }
1978
- }
1979
- /**
1980
- * Get a session and a page of its transcript.
1981
- *
1982
- * The transcript pages backwards: `beforeSeq` asks for what came before a
1983
- * message you already have.
1984
- */
1985
- async get(sessionId, params = {}, options) {
1986
- const wire = await this.call({
1987
- method: "GET",
1988
- path: runtimePath(`/sessions/${encodeURIComponent(sessionId)}`),
1989
- query: { limit: params.limit, before_seq: params.beforeSeq },
1990
- ...pickOverrides3(options)
1991
- });
1992
- return {
1993
- session: toSession(wire.session),
1994
- messages: (wire.messages ?? []).map(toSessionMessage)
1995
- };
1996
- }
1997
- /** Yield a session's messages newest first, fetching pages as you go. */
1998
- async *listAllMessages(sessionId, params = {}, options) {
1999
- const pageSize = params.limit ?? 50;
2000
- let beforeSeq = params.beforeSeq;
2001
- for (; ; ) {
2002
- const transcript = await this.get(sessionId, { limit: pageSize, beforeSeq }, options);
2003
- const messages = transcript.messages;
2004
- if (messages.length === 0) return;
2005
- yield* [...messages].sort((a, b) => b.seq - a.seq);
2006
- if (messages.length < pageSize) return;
2007
- beforeSeq = messages.reduce((lowest, m) => Math.min(lowest, m.seq), Infinity);
2008
- }
2009
- }
2010
- };
2011
- var EndUsersClient = class extends BaseClient {
2012
- /** Get an end user's budget and activity. */
2013
- async get(endUserId, options) {
2014
- const wire = await this.call({
2015
- method: "GET",
2016
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
2017
- ...pickOverrides3(options)
2018
- });
2019
- return toEndUser(wire);
2020
- }
2021
- /**
2022
- * Set an end user's budget override or metadata, creating them if needed.
2023
- *
2024
- * Fields you do not pass are left alone. Passing `null` clears the field:
2025
- * `budgetCapUsd: null` drops back to your organization's default budget.
2026
- */
2027
- async update(endUserId, params, options) {
2028
- const body = {};
2029
- if (params.budgetCapUsd !== void 0) {
2030
- body.budget_cap_usd = params.budgetCapUsd === null ? null : toMoneyString(params.budgetCapUsd);
2031
- }
2032
- if (params.metadata !== void 0) {
2033
- body.metadata = params.metadata;
2034
- }
2035
- const wire = await this.call({
2036
- method: "PUT",
2037
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
2038
- body,
2039
- ...pickOverrides3(options)
2040
- });
2041
- return toEndUser(wire);
2042
- }
2043
- /** Drop an end user's override, back to the organization default. */
2044
- async clearBudget(endUserId, options) {
2045
- return this.update(endUserId, { budgetCapUsd: null }, options);
2046
- }
2047
- };
2048
- var RuntimeSettingsClient = class extends BaseClient {
2049
- /** Read the default budget every end user starts with. */
2050
- async get(options) {
2051
- const wire = await this.call({
2052
- method: "GET",
2053
- path: runtimePath("/runtime/settings"),
2054
- ...pickOverrides3(options)
2055
- });
2056
- return toRuntimeSettings(wire);
2057
- }
2058
- /**
2059
- * Set the default budget every end user starts with.
2060
- *
2061
- * Pass `null` to remove the default, which leaves end users uncapped unless
2062
- * they have their own override.
2063
- */
2064
- async update(params, options) {
2065
- const body = {};
2066
- if (params.defaultEndUserBudgetUsd !== void 0) {
2067
- body.default_end_user_budget_usd = params.defaultEndUserBudgetUsd === null ? null : toMoneyString(params.defaultEndUserBudgetUsd);
2068
- }
2069
- const wire = await this.call({
2070
- method: "PUT",
2071
- path: runtimePath("/runtime/settings"),
2072
- body,
2073
- ...pickOverrides3(options)
2074
- });
2075
- return toRuntimeSettings(wire);
2076
- }
2077
- };
2078
- async function* readEventStream(response) {
2079
- if (!response.body) {
2080
- throw new Error("Celesto did not return a run event stream.");
2081
- }
2082
- const reader = response.body.getReader();
2083
- const textDecoder = new TextDecoder();
2084
- const sse = new SseDecoder();
2085
- let completed = false;
2086
- try {
2087
- for (; ; ) {
2088
- const chunk = await reader.read();
2089
- if (chunk.done) {
2090
- completed = true;
2091
- for (const frame of sse.push(textDecoder.decode())) {
2092
- const event = toRunEvent(frame);
2093
- if (event) yield event;
2094
- }
2095
- for (const frame of sse.flush()) {
2096
- const event = toRunEvent(frame);
2097
- if (event) yield event;
2098
- }
2099
- return;
2100
- }
2101
- for (const frame of sse.push(textDecoder.decode(chunk.value, { stream: true }))) {
2102
- const event = toRunEvent(frame);
2103
- if (event) yield event;
2104
- }
2105
- }
2106
- } finally {
2107
- if (!completed) {
2108
- try {
2109
- await reader.cancel();
2110
- } catch {
2111
- }
2112
- }
2113
- reader.releaseLock();
2114
- }
2115
- }
2116
- var ManagedAgentsClient = class {
2117
- constructor(config = {}) {
2118
- this.agents = new AgentsClient(config);
2119
- this.runs = new RunsClient(config);
2120
- this.sessions = new SessionsClient(config);
2121
- this.endUsers = new EndUsersClient(config);
2122
- this.settings = new RuntimeSettingsClient(config);
2123
- }
2124
- };
2125
829
  // Annotate the CommonJS export names for ESM import in node:
2126
830
  0 && (module.exports = {
2127
- ALLOWED_CONFIG_KEYS,
2128
- AgentArchivedError,
2129
- AgentsClient,
2130
- BudgetExceededError,
2131
831
  CelestoApiError,
2132
832
  CelestoError,
2133
833
  CelestoNetworkError,
2134
834
  Computer,
2135
- ConfigKeyNotAllowedError,
2136
- EVENTS_VERSION,
2137
- EndUsersClient,
2138
- GatekeeperClient,
2139
- IdempotencyConflictError,
2140
- KNOWN_EVENTS,
2141
835
  MISSING_CREDENTIALS_MESSAGE,
2142
- ManagedAgentError,
2143
- ManagedAgentsClient,
2144
- ModelRequiresOwnKeyError,
2145
- ProviderNotConnectedError,
2146
- RunsClient,
2147
- RuntimeSettingsClient,
2148
- SessionAgentMismatchError,
2149
- SessionBusyError,
2150
- SessionEndUserMismatchError,
2151
- SessionsClient,
2152
- eventText,
2153
- isTerminal,
2154
- parseRunEvents,
2155
- parseSseFrames,
2156
836
  resolveCelestoApiKey,
2157
- resolveClientConfig,
2158
- toRunEvent
837
+ resolveClientConfig
2159
838
  });
2160
839
  //# sourceMappingURL=index.cjs.map