@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
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,
@@ -575,92 +388,36 @@ var toSandboxTemplateInfo = (payload) => ({
575
388
  version: payload.version ?? null,
576
389
  experimental: payload.experimental
577
390
  });
578
- var diskUnitsToMb = {
579
- "": 1,
580
- m: 1,
581
- mb: 1,
582
- mib: 1,
583
- g: 1024,
584
- gb: 1024,
585
- gib: 1024,
586
- t: 1024 * 1024,
587
- tb: 1024 * 1024,
588
- tib: 1024 * 1024
589
- };
590
- var isAsciiDigit = (char) => char >= "0" && char <= "9";
591
- var isAsciiLetter = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
592
- var isSeparatorWhitespace = (char) => char === " " || char === " ";
593
- var parseDiskString = (disk) => {
594
- const value = disk.trim();
595
- if (!value) {
596
- return void 0;
597
- }
598
- let index = 0;
599
- let digitCount = 0;
600
- let hasDecimalPoint = false;
601
- while (index < value.length) {
602
- const char = value[index];
603
- if (isAsciiDigit(char)) {
604
- digitCount += 1;
605
- index += 1;
606
- 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.`);
607
406
  }
608
- if (char === "." && !hasDecimalPoint) {
609
- hasDecimalPoint = true;
610
- index += 1;
611
- continue;
407
+ if (!createOptions.has(field)) {
408
+ throw new TypeError(`Unknown computer create option ${JSON.stringify(field)}. Remove it and retry.`);
612
409
  }
613
- break;
614
- }
615
- if (digitCount === 0 || value[index - 1] === ".") {
616
- return void 0;
617
- }
618
- const amount = value.slice(0, index);
619
- while (index < value.length && isSeparatorWhitespace(value[index])) {
620
- index += 1;
621
410
  }
622
- const unit = value.slice(index);
623
- if ([...unit].some((char) => !isAsciiLetter(char))) {
624
- return void 0;
625
- }
626
- return { amount, unit };
627
- };
628
- var parseDiskSizeMb = (disk) => {
629
- if (disk === void 0) {
630
- 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.");
631
413
  }
632
- if (typeof disk === "number") {
633
- if (!Number.isInteger(disk) || disk <= 0) {
634
- 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".');
635
418
  }
636
- return disk;
637
- }
638
- const parsedDisk = parseDiskString(disk);
639
- if (!parsedDisk) {
640
- throw new Error("disk must be a size in MB or a string like '2gb'.");
641
- }
642
- const multiplier = diskUnitsToMb[parsedDisk.unit.toLowerCase()];
643
- if (multiplier === void 0) {
644
- throw new Error("disk must use MB, GB, or TB, for example '2048mb' or '2gb'.");
645
- }
646
- const sizeMb = Number(parsedDisk.amount) * multiplier;
647
- if (!Number.isInteger(sizeMb) || sizeMb <= 0) {
648
- throw new Error("disk must resolve to a whole number of MB, for example '1536mb' or '1.5gb'.");
649
- }
650
- return sizeMb;
651
- };
652
- var buildCreateComputerBody = (params) => {
653
- if (params.cpus !== void 0 && params.vcpus !== void 0 && params.cpus !== params.vcpus) {
654
- throw new Error("cpus and vcpus must have the same value when both are provided.");
655
- }
656
- if (params.memory !== void 0 && params.ramMb !== void 0 && params.memory !== params.ramMb) {
657
- throw new Error("memory and ramMb must have the same value when both are provided.");
419
+ body.size_id = params.sizeId;
658
420
  }
659
- const parsedDiskSizeMb = parseDiskSizeMb(params.disk);
660
- if (parsedDiskSizeMb !== void 0 && params.diskSizeMb !== void 0 && parsedDiskSizeMb !== params.diskSizeMb) {
661
- throw new Error("disk and diskSizeMb must have the same value when both are provided.");
662
- }
663
- const body = {};
664
421
  if (params.networkPolicy !== void 0) {
665
422
  const policy = params.networkPolicy;
666
423
  if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
@@ -671,18 +428,6 @@ var buildCreateComputerBody = (params) => {
671
428
  }
672
429
  body.network_policy = { mode: policy.mode };
673
430
  }
674
- const vcpus = params.vcpus ?? params.cpus;
675
- const ramMb = params.ramMb ?? params.memory;
676
- const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
677
- if (vcpus !== void 0) {
678
- body.vcpus = vcpus;
679
- }
680
- if (ramMb !== void 0) {
681
- body.ram_mb = ramMb;
682
- }
683
- if (diskSizeMb !== void 0) {
684
- body.disk_size_mb = diskSizeMb;
685
- }
686
431
  if (params.image !== void 0) {
687
432
  body.image = params.image;
688
433
  }
@@ -698,114 +443,35 @@ var buildCreateComputerBody = (params) => {
698
443
  return body;
699
444
  };
700
445
  var computersPath = (path2) => `/v1/computers${path2}`;
701
- var pickOverrides2 = (options) => ({
446
+ var pickOverrides = (options) => ({
702
447
  headers: options?.headers,
703
448
  signal: options?.signal
704
449
  });
705
- var optionalNumber = (value) => typeof value === "number" ? value : void 0;
706
- var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
707
- var parseExecStreamEvent = (value) => {
708
- if (!value || typeof value !== "object") {
709
- throw new Error("Celesto returned an invalid command stream event.");
710
- }
711
- const event = value;
712
- if (event.type === "stdout" || event.type === "stderr") {
713
- if (typeof event.data !== "string") {
714
- throw new Error("Celesto returned command output without text data.");
715
- }
716
- return { type: event.type, data: event.data };
717
- }
718
- if (event.type === "started") {
719
- if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
720
- throw new Error("Celesto returned an invalid command-start event.");
721
- }
722
- return {
723
- type: "started",
724
- commandId: event.command_id,
725
- startedAtUnixMs: event.started_at_unix_ms,
726
- timeoutSeconds: event.timeout_seconds
727
- };
728
- }
729
- if (event.type === "exit") {
730
- if (typeof event.exit_code !== "number") {
731
- throw new Error("Celesto returned an invalid command-exit event.");
732
- }
733
- const result = {
734
- type: "exit",
735
- exitCode: event.exit_code
736
- };
737
- if (typeof event.command_id === "string") result.commandId = event.command_id;
738
- const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
739
- const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
740
- const durationMs = optionalNumber(event.duration_ms);
741
- const timedOut = optionalBoolean(event.timed_out);
742
- if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
743
- if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
744
- if (durationMs !== void 0) result.durationMs = durationMs;
745
- if (timedOut !== void 0) result.timedOut = timedOut;
746
- return result;
747
- }
748
- throw new Error("Celesto returned an unknown command stream event.");
749
- };
750
- var parseSseDataLine = (line) => {
751
- const text = line.trim();
752
- if (!text || !text.startsWith("data:")) {
753
- return void 0;
754
- }
755
- const data = text.slice("data:".length).trim();
756
- if (!data || data === "[DONE]") {
757
- return void 0;
758
- }
759
- try {
760
- return parseExecStreamEvent(JSON.parse(data));
761
- } catch (error) {
762
- if (error instanceof SyntaxError) {
763
- throw new Error("Celesto returned malformed JSON in the command stream.");
764
- }
765
- throw error;
766
- }
767
- };
768
- var createManagedSignal = (signal, timeoutMs) => {
769
- if (!timeoutMs || timeoutMs <= 0) {
770
- return { signal, cleanup: () => {
771
- } };
772
- }
773
- const controller = new AbortController();
774
- const abort = () => controller.abort();
775
- if (signal?.aborted) {
776
- abort();
777
- } else {
778
- signal?.addEventListener("abort", abort, { once: true });
779
- }
780
- const timer = setTimeout(abort, timeoutMs);
781
- return {
782
- signal: controller.signal,
783
- cleanup: () => {
784
- clearTimeout(timer);
785
- signal?.removeEventListener("abort", abort);
786
- }
787
- };
788
- };
789
- var toNetworkError = (error) => {
790
- if (error instanceof CelestoNetworkError) return error;
791
- const cause = error instanceof Error ? error : new Error(String(error));
792
- return new CelestoNetworkError(cause.message, cause);
793
- };
794
- var withFallbackCommandId = (event, commandId) => {
795
- if (event.type !== "exit" || event.commandId || !commandId) return event;
796
- return { ...event, commandId };
797
- };
798
450
  var ComputersClient = class {
799
451
  constructor(config) {
800
452
  this.config = config;
801
453
  }
802
454
  async create(params = {}, options) {
803
455
  const ctx = buildRequestContext(this.config);
804
- 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 }, {
805
470
  method: "POST",
806
471
  path: computersPath(""),
807
472
  body: buildCreateComputerBody(params),
808
- ...pickOverrides2(options)
473
+ headers,
474
+ signal: options?.signal
809
475
  });
810
476
  return toComputerInfo(data);
811
477
  }
@@ -814,7 +480,7 @@ var ComputersClient = class {
814
480
  const data = await request(ctx, {
815
481
  method: "GET",
816
482
  path: computersPath("/templates"),
817
- ...pickOverrides2(options)
483
+ ...pickOverrides(options)
818
484
  });
819
485
  return data.map(toSandboxTemplateInfo);
820
486
  }
@@ -829,7 +495,7 @@ var ComputersClient = class {
829
495
  project_id: params.projectId,
830
496
  limit: params.limit
831
497
  },
832
- ...pickOverrides2(options)
498
+ ...pickOverrides(options)
833
499
  });
834
500
  return {
835
501
  computers: data.computers.map(toComputerInfo),
@@ -841,105 +507,48 @@ var ComputersClient = class {
841
507
  const data = await request(ctx, {
842
508
  method: "GET",
843
509
  path: computersPath(`/${encodeURIComponent(computerId)}`),
844
- ...pickOverrides2(options)
510
+ ...pickOverrides(options)
845
511
  });
846
512
  return toComputerInfo(data);
847
513
  }
848
514
  async exec(computerId, command, params = {}, options) {
849
- const ctx = buildRequestContext(this.config);
850
- const managedSignal = createManagedSignal(
851
- params.signal ?? options?.signal,
852
- this.config.timeoutMs
853
- );
854
- try {
855
- const data = await request(ctx, {
856
- method: "POST",
857
- path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
858
- body: {
859
- command,
860
- timeout: params.timeout ?? 30
861
- },
862
- headers: options?.headers,
863
- signal: managedSignal.signal
864
- });
865
- return toExecResponse(data);
866
- } finally {
867
- managedSignal.cleanup();
868
- }
869
- }
870
- async *execStream(computerId, command, params = {}, options) {
871
- const ctx = buildRequestContext(this.config);
872
- const managedSignal = createManagedSignal(
873
- params.signal ?? options?.signal,
874
- this.config.timeoutMs
875
- );
876
- let reader;
877
- let completed = false;
878
- try {
879
- const response = await requestStream(ctx, {
880
- method: "POST",
881
- path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
882
- body: {
883
- command,
884
- timeout: params.timeout ?? 30
885
- },
886
- headers: options?.headers,
887
- signal: managedSignal.signal
888
- });
889
- if (!response.body) {
890
- throw new Error("Celesto did not return a command output stream.");
891
- }
892
- const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
893
- reader = response.body.getReader();
894
- const decoder = new TextDecoder();
895
- let buffer = "";
896
- while (true) {
897
- let chunk;
898
- try {
899
- chunk = await reader.read();
900
- } catch (error) {
901
- throw toNetworkError(error);
902
- }
903
- if (chunk.done) {
904
- completed = true;
905
- buffer += decoder.decode();
906
- break;
907
- }
908
- buffer += decoder.decode(chunk.value, { stream: true });
909
- let newlineIndex = buffer.indexOf("\n");
910
- while (newlineIndex !== -1) {
911
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
912
- buffer = buffer.slice(newlineIndex + 1);
913
- const parsed = parseSseDataLine(line);
914
- if (parsed) {
915
- const event = withFallbackCommandId(parsed, responseCommandId);
916
- yield event;
917
- if (event.type === "exit") return;
918
- }
919
- newlineIndex = buffer.indexOf("\n");
920
- }
921
- }
922
- if (buffer) {
923
- const parsed = parseSseDataLine(buffer);
924
- if (parsed) {
925
- const event = withFallbackCommandId(parsed, responseCommandId);
926
- yield event;
927
- if (event.type === "exit") return;
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.");
928
523
  }
929
524
  }
930
- throw new Error("Command stream ended before Celesto returned an exit status.");
931
- } finally {
932
- if (reader) {
933
- if (!completed) {
934
- try {
935
- await reader.cancel();
936
- } catch {
937
- }
938
- }
939
- reader.releaseLock();
940
- }
941
- managedSignal.cleanup();
942
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
+ };
943
552
  }
944
553
  async listCommandHistory(computerId, params = {}, options) {
945
554
  const ctx = buildRequestContext(this.config);
@@ -947,7 +556,7 @@ var ComputersClient = class {
947
556
  method: "GET",
948
557
  path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
949
558
  query: { limit: params.limit },
950
- ...pickOverrides2(options)
559
+ ...pickOverrides(options)
951
560
  });
952
561
  return {
953
562
  commands: data.commands.map(toCommandHistoryEntry),
@@ -959,7 +568,7 @@ var ComputersClient = class {
959
568
  const data = await request(ctx, {
960
569
  method: "POST",
961
570
  path: computersPath(`/${encodeURIComponent(computerId)}/stop`),
962
- ...pickOverrides2(options)
571
+ ...pickOverrides(options)
963
572
  });
964
573
  return toComputerInfo(data);
965
574
  }
@@ -968,7 +577,7 @@ var ComputersClient = class {
968
577
  const data = await request(ctx, {
969
578
  method: "POST",
970
579
  path: computersPath(`/${encodeURIComponent(computerId)}/start`),
971
- ...pickOverrides2(options)
580
+ ...pickOverrides(options)
972
581
  });
973
582
  return toComputerInfo(data);
974
583
  }
@@ -977,7 +586,7 @@ var ComputersClient = class {
977
586
  const data = await request(ctx, {
978
587
  method: "DELETE",
979
588
  path: computersPath(`/${encodeURIComponent(computerId)}`),
980
- ...pickOverrides2(options)
589
+ ...pickOverrides(options)
981
590
  });
982
591
  return toComputerInfo(data);
983
592
  }
@@ -987,7 +596,7 @@ var ComputersClient = class {
987
596
  method: "POST",
988
597
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
989
598
  body: { port },
990
- ...pickOverrides2(options)
599
+ ...pickOverrides(options)
991
600
  });
992
601
  return toPublishedPortInfo(data);
993
602
  }
@@ -996,7 +605,7 @@ var ComputersClient = class {
996
605
  const data = await request(ctx, {
997
606
  method: "GET",
998
607
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports`),
999
- ...pickOverrides2(options)
608
+ ...pickOverrides(options)
1000
609
  });
1001
610
  return data.map(toPublishedPortInfo);
1002
611
  }
@@ -1005,7 +614,7 @@ var ComputersClient = class {
1005
614
  const data = await request(ctx, {
1006
615
  method: "DELETE",
1007
616
  path: computersPath(`/${encodeURIComponent(computerId)}/published-ports/${port}`),
1008
- ...pickOverrides2(options)
617
+ ...pickOverrides(options)
1009
618
  });
1010
619
  return toPublishedPortInfo(data);
1011
620
  }
@@ -1015,7 +624,7 @@ var ComputersClient = class {
1015
624
  const data = await request(ctx, {
1016
625
  method: "POST",
1017
626
  path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
1018
- ...pickOverrides2(options)
627
+ ...pickOverrides(options)
1019
628
  });
1020
629
  return toTerminalConnectionInfo(data);
1021
630
  }
@@ -1025,7 +634,7 @@ var ComputersClient = class {
1025
634
  const data = await request(ctx, {
1026
635
  method: "POST",
1027
636
  path: computersPath(`/${encodeURIComponent(computerIdOrName)}/browser`),
1028
- ...pickOverrides2(options)
637
+ ...pickOverrides(options)
1029
638
  });
1030
639
  return toBrowserConnectionInfo(data);
1031
640
  }
@@ -1036,7 +645,7 @@ var ComputersClient = class {
1036
645
  method: "POST",
1037
646
  path: computersPath(`/${encodeURIComponent(computerIdOrName)}/display`),
1038
647
  body: params.mode === void 0 ? void 0 : { mode: params.mode },
1039
- ...pickOverrides2(options)
648
+ ...pickOverrides(options)
1040
649
  });
1041
650
  return toDisplayConnectionInfo(data);
1042
651
  }
@@ -1091,6 +700,9 @@ var Computer = class _Computer {
1091
700
  get status() {
1092
701
  return this.info.status;
1093
702
  }
703
+ get sizeId() {
704
+ return this.info.sizeId;
705
+ }
1094
706
  get vcpus() {
1095
707
  return this.info.vcpus;
1096
708
  }
@@ -1145,7 +757,7 @@ var Computer = class _Computer {
1145
757
  async exec(command, params = {}) {
1146
758
  return this.run(command, params);
1147
759
  }
1148
- /** 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. */
1149
761
  runStream(command, params = {}) {
1150
762
  return this.client.execStream(this.id, command, params);
1151
763
  }
@@ -1214,1008 +826,14 @@ var Computer = class _Computer {
1214
826
  return unpublished;
1215
827
  }
1216
828
  };
1217
-
1218
- // src/agents/errors.ts
1219
- var ManagedAgentError = class extends CelestoApiError {
1220
- constructor(message, status, data, options = {}) {
1221
- super(message, status, data, options.requestId, options.headers);
1222
- /** True when retrying the identical request can succeed. */
1223
- this.retryable = false;
1224
- this.name = "ManagedAgentError";
1225
- this.code = options.code;
1226
- this.retryAfter = options.retryAfter;
1227
- }
1228
- };
1229
- var BudgetExceededError = class extends ManagedAgentError {
1230
- constructor(...args) {
1231
- super(...args);
1232
- this.name = "BudgetExceededError";
1233
- }
1234
- };
1235
- var SessionBusyError = class extends ManagedAgentError {
1236
- constructor(...args) {
1237
- super(...args);
1238
- this.retryable = true;
1239
- this.name = "SessionBusyError";
1240
- }
1241
- };
1242
- var IdempotencyConflictError = class extends ManagedAgentError {
1243
- constructor(...args) {
1244
- super(...args);
1245
- this.name = "IdempotencyConflictError";
1246
- }
1247
- };
1248
- var AgentArchivedError = class extends ManagedAgentError {
1249
- constructor(...args) {
1250
- super(...args);
1251
- this.name = "AgentArchivedError";
1252
- }
1253
- };
1254
- var ProviderNotConnectedError = class extends ManagedAgentError {
1255
- constructor(...args) {
1256
- super(...args);
1257
- this.name = "ProviderNotConnectedError";
1258
- }
1259
- };
1260
- var SessionAgentMismatchError = class extends ManagedAgentError {
1261
- constructor(...args) {
1262
- super(...args);
1263
- this.name = "SessionAgentMismatchError";
1264
- }
1265
- };
1266
- var SessionEndUserMismatchError = class extends ManagedAgentError {
1267
- constructor(...args) {
1268
- super(...args);
1269
- this.name = "SessionEndUserMismatchError";
1270
- }
1271
- };
1272
- var ModelRequiresOwnKeyError = class extends ManagedAgentError {
1273
- constructor(...args) {
1274
- super(...args);
1275
- this.name = "ModelRequiresOwnKeyError";
1276
- }
1277
- };
1278
- var ConfigKeyNotAllowedError = class extends ManagedAgentError {
1279
- constructor(...args) {
1280
- super(...args);
1281
- this.name = "ConfigKeyNotAllowedError";
1282
- }
1283
- };
1284
- var ERROR_CLASSES = {
1285
- budget_exceeded: BudgetExceededError,
1286
- session_busy: SessionBusyError,
1287
- idempotency_conflict: IdempotencyConflictError,
1288
- agent_archived: AgentArchivedError,
1289
- provider_not_connected: ProviderNotConnectedError,
1290
- session_agent_mismatch: SessionAgentMismatchError,
1291
- session_end_user_mismatch: SessionEndUserMismatchError,
1292
- model_requires_own_key: ModelRequiresOwnKeyError,
1293
- config_key_not_allowed: ConfigKeyNotAllowedError
1294
- };
1295
- var STATUS_FALLBACK = {
1296
- 402: BudgetExceededError
1297
- };
1298
- var readErrorCode = (data) => {
1299
- if (!data || typeof data !== "object") return void 0;
1300
- const record = data;
1301
- const detail = record.detail;
1302
- const raw = detail && typeof detail === "object" ? detail.code : record.code;
1303
- if (typeof raw !== "string") return void 0;
1304
- return raw in ERROR_CLASSES ? raw : void 0;
1305
- };
1306
- var readMessage = (data, fallback) => {
1307
- if (data && typeof data === "object") {
1308
- const detail = data.detail;
1309
- if (detail && typeof detail === "object") {
1310
- const message = detail.message;
1311
- if (typeof message === "string") return message;
1312
- }
1313
- }
1314
- return fallback;
1315
- };
1316
- var readRetryAfter = (headers) => {
1317
- const raw = headers?.get("retry-after");
1318
- if (!raw) return void 0;
1319
- const seconds = Number(raw);
1320
- return Number.isFinite(seconds) ? seconds : void 0;
1321
- };
1322
- var toManagedAgentError = (error) => {
1323
- if (!(error instanceof CelestoApiError) || error instanceof ManagedAgentError) {
1324
- return error;
1325
- }
1326
- const code = readErrorCode(error.data);
1327
- const ErrorClass = (code && ERROR_CLASSES[code]) ?? STATUS_FALLBACK[error.status];
1328
- if (!ErrorClass) return error;
1329
- return new ErrorClass(readMessage(error.data, error.message), error.status, error.data, {
1330
- code: code ?? (error.status === 402 ? "budget_exceeded" : void 0),
1331
- retryAfter: readRetryAfter(error.headers),
1332
- requestId: error.requestId,
1333
- headers: error.headers
1334
- });
1335
- };
1336
-
1337
- // src/agents/events.ts
1338
- var EVENTS_VERSION = "1";
1339
- var KNOWN_EVENTS = [
1340
- "run.started",
1341
- "message.delta",
1342
- "message.completed",
1343
- "tool.call",
1344
- "tool.result",
1345
- "usage",
1346
- "run.completed",
1347
- "run.failed"
1348
- ];
1349
- var KNOWN_EVENT_SET = new Set(KNOWN_EVENTS);
1350
- var asRecord = (value) => value && typeof value === "object" ? value : {};
1351
- var str = (value) => typeof value === "string" ? value : null;
1352
- var num = (value) => typeof value === "number" ? value : null;
1353
- var int = (value) => typeof value === "number" ? value : 0;
1354
- var money = (value) => typeof value === "string" ? value : "0.000000";
1355
- var toUsage = (value) => {
1356
- const raw = asRecord(value);
1357
- return {
1358
- inputTokens: int(raw.input_tokens),
1359
- outputTokens: int(raw.output_tokens),
1360
- totalTokens: int(raw.total_tokens),
1361
- costUsd: money(raw.cost_usd)
1362
- };
1363
- };
1364
- var toToolResultData = (raw) => {
1365
- const data = {
1366
- callId: str(raw.call_id),
1367
- name: str(raw.name),
1368
- turn: num(raw.turn)
1369
- };
1370
- if ("error" in raw) {
1371
- data.error = raw.error;
1372
- } else {
1373
- data.result = raw.result;
1374
- }
1375
- return data;
1376
- };
1377
- var toRunEvent = (frame) => {
1378
- const name = frame.event;
1379
- if (!name || !KNOWN_EVENT_SET.has(name)) return void 0;
1380
- let parsed;
1381
- try {
1382
- parsed = frame.data ? JSON.parse(frame.data) : {};
1383
- } catch {
1384
- return void 0;
1385
- }
1386
- const raw = asRecord(parsed);
1387
- const seq = frame.id !== void 0 && frame.id !== "" ? Number(frame.id) : NaN;
1388
- const position = Number.isFinite(seq) ? seq : null;
1389
- switch (name) {
1390
- case "run.started":
1391
- return {
1392
- name: "run.started",
1393
- seq: position,
1394
- data: {
1395
- runId: str(raw.run_id) ?? "",
1396
- agentId: str(raw.agent_id) ?? "",
1397
- agentVersionId: str(raw.agent_version_id) ?? "",
1398
- sessionId: str(raw.session_id) ?? "",
1399
- endUserId: str(raw.end_user_id) ?? "",
1400
- model: str(raw.model) ?? "",
1401
- createdAt: str(raw.created_at) ?? ""
1402
- }
1403
- };
1404
- case "message.delta":
1405
- return {
1406
- name: "message.delta",
1407
- seq: position,
1408
- data: { text: str(raw.text), turn: num(raw.turn) }
1409
- };
1410
- case "message.completed":
1411
- return {
1412
- name: "message.completed",
1413
- seq: position,
1414
- data: { text: str(raw.text), turn: num(raw.turn) }
1415
- };
1416
- case "tool.call":
1417
- return {
1418
- name: "tool.call",
1419
- seq: position,
1420
- data: {
1421
- callId: str(raw.call_id),
1422
- name: str(raw.name),
1423
- args: raw.args,
1424
- turn: num(raw.turn)
1425
- }
1426
- };
1427
- case "tool.result":
1428
- return { name: "tool.result", seq: position, data: toToolResultData(raw) };
1429
- case "usage":
1430
- return {
1431
- name: "usage",
1432
- seq: position,
1433
- data: {
1434
- turn: num(raw.turn),
1435
- model: str(raw.model),
1436
- inputTokens: int(raw.input_tokens),
1437
- outputTokens: int(raw.output_tokens),
1438
- totalTokens: int(raw.total_tokens),
1439
- costUsd: money(raw.cost_usd)
1440
- }
1441
- };
1442
- case "run.completed":
1443
- return {
1444
- name: "run.completed",
1445
- seq: position,
1446
- data: {
1447
- runId: str(raw.run_id) ?? "",
1448
- status: str(raw.status) ?? "completed",
1449
- output: str(raw.output),
1450
- turnCount: num(raw.turn_count),
1451
- usage: toUsage(raw.usage)
1452
- }
1453
- };
1454
- case "run.failed":
1455
- return {
1456
- name: "run.failed",
1457
- seq: position,
1458
- data: {
1459
- runId: str(raw.run_id) ?? "",
1460
- status: str(raw.status) ?? "failed",
1461
- errorCode: str(raw.error_code),
1462
- error: str(raw.error),
1463
- turnCount: num(raw.turn_count),
1464
- usage: toUsage(raw.usage)
1465
- }
1466
- };
1467
- default:
1468
- return void 0;
1469
- }
1470
- };
1471
- var isTerminal = (event) => event.name === "run.completed" || event.name === "run.failed";
1472
- var eventText = (event) => {
1473
- switch (event.name) {
1474
- case "message.delta":
1475
- case "message.completed":
1476
- return event.data.text ?? "";
1477
- case "run.completed":
1478
- return event.data.output ?? "";
1479
- default:
1480
- return "";
1481
- }
1482
- };
1483
- var SseDecoder = class {
1484
- constructor() {
1485
- this.buffer = "";
1486
- }
1487
- push(chunk) {
1488
- this.buffer += chunk;
1489
- const frames = [];
1490
- let boundary = this.findBoundary();
1491
- while (boundary) {
1492
- const block = this.buffer.slice(0, boundary.index);
1493
- this.buffer = this.buffer.slice(boundary.index + boundary.length);
1494
- const frame = parseFrame(block);
1495
- if (frame) frames.push(frame);
1496
- boundary = this.findBoundary();
1497
- }
1498
- return frames;
1499
- }
1500
- /** Anything left in the buffer when the stream ends. */
1501
- flush() {
1502
- const block = this.buffer;
1503
- this.buffer = "";
1504
- const frame = parseFrame(block);
1505
- return frame ? [frame] : [];
1506
- }
1507
- findBoundary() {
1508
- const lf = this.buffer.indexOf("\n\n");
1509
- const crlf = this.buffer.indexOf("\r\n\r\n");
1510
- if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
1511
- if (lf !== -1) return { index: lf, length: 2 };
1512
- return void 0;
1513
- }
1514
- };
1515
- var parseFrame = (block) => {
1516
- let event;
1517
- let id;
1518
- const dataLines = [];
1519
- let sawField = false;
1520
- for (const rawLine of block.split("\n")) {
1521
- const line = rawLine.replace(/\r$/, "");
1522
- if (line === "" || line.startsWith(":")) continue;
1523
- const separator = line.indexOf(":");
1524
- const field = separator === -1 ? line : line.slice(0, separator);
1525
- let value = separator === -1 ? "" : line.slice(separator + 1);
1526
- if (value.startsWith(" ")) value = value.slice(1);
1527
- if (field === "event") {
1528
- event = value;
1529
- sawField = true;
1530
- } else if (field === "data") {
1531
- dataLines.push(value);
1532
- sawField = true;
1533
- } else if (field === "id") {
1534
- id = value;
1535
- sawField = true;
1536
- }
1537
- }
1538
- if (!sawField) return void 0;
1539
- const frame = { data: dataLines.join("\n") };
1540
- if (event !== void 0) frame.event = event;
1541
- if (id !== void 0) frame.id = id;
1542
- return frame;
1543
- };
1544
- var parseSseFrames = (body) => {
1545
- const decoder = new SseDecoder();
1546
- return [...decoder.push(body), ...decoder.flush()];
1547
- };
1548
- var parseRunEvents = (body) => {
1549
- const events = [];
1550
- for (const frame of parseSseFrames(body)) {
1551
- const event = toRunEvent(frame);
1552
- if (event) events.push(event);
1553
- }
1554
- return events;
1555
- };
1556
-
1557
- // src/agents/client.ts
1558
- var runtimePath = (path2) => `/v1${path2}`;
1559
- var pickOverrides3 = (options) => ({
1560
- headers: options?.headers,
1561
- signal: options?.signal
1562
- });
1563
- var DEFAULT_RETRY_BACKOFF_MS = 1e3;
1564
- var CONFIG_KEYS = {
1565
- temperature: "temperature",
1566
- topP: "top_p",
1567
- maxTokens: "max_tokens",
1568
- maxOutputTokens: "max_output_tokens",
1569
- frequencyPenalty: "frequency_penalty",
1570
- presencePenalty: "presence_penalty",
1571
- seed: "seed",
1572
- stop: "stop",
1573
- reasoningEffort: "reasoning_effort",
1574
- verbosity: "verbosity",
1575
- maxTurns: "max_turns"
1576
- };
1577
- var ALLOWED_CONFIG_KEYS = Object.keys(CONFIG_KEYS);
1578
- var WIRE_TO_CONFIG_KEY = new Map(
1579
- Object.entries(CONFIG_KEYS).map(([key, wire]) => [
1580
- wire,
1581
- key
1582
- ])
1583
- );
1584
- var toConfigWire = (config) => {
1585
- if (!config) return void 0;
1586
- const wire = {};
1587
- const unknown = [];
1588
- for (const [key, value] of Object.entries(config)) {
1589
- if (value === void 0) continue;
1590
- const wireKey = CONFIG_KEYS[key];
1591
- if (!wireKey) {
1592
- unknown.push(key);
1593
- continue;
1594
- }
1595
- wire[wireKey] = value;
1596
- }
1597
- if (unknown.length > 0) {
1598
- throw new ConfigKeyNotAllowedError(
1599
- `Agent config does not accept ${unknown.join(", ")}. It accepts only: ${ALLOWED_CONFIG_KEYS.join(", ")}.`,
1600
- 422,
1601
- void 0,
1602
- { code: "config_key_not_allowed" }
1603
- );
1604
- }
1605
- return wire;
1606
- };
1607
- var toConfig = (wire) => {
1608
- if (!wire || typeof wire !== "object") return null;
1609
- const config = {};
1610
- for (const [wireKey, value] of Object.entries(wire)) {
1611
- const key = WIRE_TO_CONFIG_KEY.get(wireKey);
1612
- config[key ?? wireKey] = value;
1613
- }
1614
- return config;
1615
- };
1616
- var toAgent = (wire) => ({
1617
- id: wire.id,
1618
- object: wire.object ?? "agent",
1619
- name: wire.name,
1620
- description: wire.description ?? null,
1621
- model: wire.model,
1622
- instructions: wire.instructions ?? null,
1623
- config: toConfig(wire.config),
1624
- version: wire.version,
1625
- currentVersionId: wire.current_version_id,
1626
- projectId: wire.project_id,
1627
- organizationId: wire.organization_id,
1628
- status: wire.status,
1629
- createdAt: wire.created_at,
1630
- updatedAt: wire.updated_at
1631
- });
1632
- var toAgentVersion = (wire) => ({
1633
- id: wire.id,
1634
- object: wire.object ?? "agent_version",
1635
- agentId: wire.agent_id,
1636
- version: wire.version,
1637
- name: wire.name,
1638
- description: wire.description ?? null,
1639
- model: wire.model,
1640
- instructions: wire.instructions ?? null,
1641
- config: toConfig(wire.config),
1642
- createdAt: wire.created_at
1643
- });
1644
- var toUsage2 = (wire) => ({
1645
- inputTokens: wire.input_tokens,
1646
- outputTokens: wire.output_tokens,
1647
- totalTokens: wire.total_tokens,
1648
- // Money stays a string. Never parseFloat this.
1649
- costUsd: wire.cost_usd
1650
- });
1651
- var toRun = (wire) => ({
1652
- runId: wire.run_id,
1653
- object: wire.object ?? "run",
1654
- status: wire.status,
1655
- errorCode: wire.error_code ?? null,
1656
- error: wire.error ?? null,
1657
- output: wire.output ?? null,
1658
- usage: toUsage2(wire.usage),
1659
- agentId: wire.agent_id,
1660
- agentVersionId: wire.agent_version_id,
1661
- sessionId: wire.session_id,
1662
- endUserId: wire.end_user_id,
1663
- turnCount: wire.turn_count ?? null,
1664
- createdAt: wire.created_at,
1665
- startedAt: wire.started_at ?? null,
1666
- endedAt: wire.ended_at ?? null
1667
- });
1668
- var toSession = (wire) => ({
1669
- id: wire.id,
1670
- object: wire.object ?? "session",
1671
- agentId: wire.agent_id ?? null,
1672
- endUserId: wire.end_user_id,
1673
- status: wire.status,
1674
- messageCount: wire.message_count,
1675
- lastMessageAt: wire.last_message_at ?? null,
1676
- createdAt: wire.created_at
1677
- });
1678
- var toSessionMessage = (wire) => ({
1679
- seq: wire.seq,
1680
- role: wire.role ?? null,
1681
- item: wire.item,
1682
- createdAt: wire.created_at
1683
- });
1684
- var toBudget = (wire) => ({
1685
- capUsd: wire.cap_usd ?? null,
1686
- source: wire.source,
1687
- windowStart: wire.window_start,
1688
- windowResetsAt: wire.window_resets_at,
1689
- spentUsd: wire.spent_usd,
1690
- remainingUsd: wire.remaining_usd ?? null
1691
- });
1692
- var toEndUser = (wire) => ({
1693
- endUserId: wire.end_user_id,
1694
- object: wire.object ?? "end_user",
1695
- firstActivityAt: wire.first_activity_at,
1696
- budget: toBudget(wire.budget),
1697
- metadata: wire.metadata ?? null,
1698
- createdAt: wire.created_at
1699
- });
1700
- var toRuntimeSettings = (wire) => ({
1701
- organizationId: wire.organization_id,
1702
- defaultEndUserBudgetUsd: wire.default_end_user_budget_usd ?? null
1703
- });
1704
- var toPage = (wire, map) => ({
1705
- data: (wire.data ?? []).map(map),
1706
- hasMore: wire.has_more ?? false
1707
- });
1708
- var MONEY_PATTERN = /^\d{1,8}(\.\d{1,6})?$/;
1709
- var toMoneyString = (value) => {
1710
- if (typeof value === "number") {
1711
- throw new TypeError(
1712
- `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.`
1713
- );
1714
- }
1715
- const text = value.trim();
1716
- if (!MONEY_PATTERN.test(text)) {
1717
- throw new TypeError(
1718
- `"${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.`
1719
- );
1720
- }
1721
- return text;
1722
- };
1723
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1724
- var newIdempotencyKey = () => {
1725
- const uuid = globalThis.crypto?.randomUUID?.();
1726
- return uuid ?? `idem_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1727
- };
1728
- var BaseClient = class {
1729
- constructor(config) {
1730
- this.config = config;
1731
- }
1732
- /** Every call goes through here, so refusals arrive already typed. */
1733
- async call(options) {
1734
- try {
1735
- return await request(buildRequestContext(this.config), options);
1736
- } catch (error) {
1737
- throw toManagedAgentError(error);
1738
- }
1739
- }
1740
- };
1741
- var AgentsClient = class extends BaseClient {
1742
- /** Create an agent, at version 1. */
1743
- async create(params, options) {
1744
- const wire = await this.call({
1745
- method: "POST",
1746
- path: runtimePath("/agents"),
1747
- body: {
1748
- name: params.name,
1749
- model: params.model,
1750
- instructions: params.instructions,
1751
- description: params.description,
1752
- config: toConfigWire(params.config),
1753
- project_id: params.projectId
1754
- },
1755
- ...pickOverrides3(options)
1756
- });
1757
- return toAgent(wire);
1758
- }
1759
- /** List one page of agents. Check `hasMore`; there is no total count. */
1760
- async list(params = {}, options) {
1761
- const wire = await this.call({
1762
- method: "GET",
1763
- path: runtimePath("/agents"),
1764
- query: {
1765
- project_id: params.projectId,
1766
- include_archived: params.includeArchived,
1767
- limit: params.limit,
1768
- offset: params.offset
1769
- },
1770
- ...pickOverrides3(options)
1771
- });
1772
- return toPage(wire, toAgent);
1773
- }
1774
- /** Yield every agent, fetching pages as you go. */
1775
- async *listAll(params = {}, options) {
1776
- const pageSize = params.limit ?? 50;
1777
- let offset = 0;
1778
- for (; ; ) {
1779
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
1780
- yield* page.data;
1781
- if (page.data.length === 0 || !page.hasMore) return;
1782
- offset += page.data.length;
1783
- }
1784
- }
1785
- /** Get an agent, at its current version. */
1786
- async get(agentId, options) {
1787
- const wire = await this.call({
1788
- method: "GET",
1789
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1790
- ...pickOverrides3(options)
1791
- });
1792
- return toAgent(wire);
1793
- }
1794
- /**
1795
- * Replace an agent's definition, which cuts a new version.
1796
- *
1797
- * This is a full replacement, not a patch: whatever you leave out is
1798
- * cleared. Read the agent first if you only mean to change one field.
1799
- */
1800
- async update(agentId, params, options) {
1801
- const wire = await this.call({
1802
- method: "PUT",
1803
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1804
- body: {
1805
- name: params.name,
1806
- model: params.model,
1807
- instructions: params.instructions,
1808
- description: params.description,
1809
- config: toConfigWire(params.config)
1810
- },
1811
- ...pickOverrides3(options)
1812
- });
1813
- return toAgent(wire);
1814
- }
1815
- /**
1816
- * Archive an agent. Archived agents refuse new runs.
1817
- *
1818
- * Past runs, versions, and transcripts stay readable.
1819
- */
1820
- async archive(agentId, options) {
1821
- const wire = await this.call({
1822
- method: "DELETE",
1823
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
1824
- ...pickOverrides3(options)
1825
- });
1826
- return { id: wire.id, status: wire.status };
1827
- }
1828
- /** List one page of an agent's versions. */
1829
- async listVersions(agentId, params = {}, options) {
1830
- const wire = await this.call({
1831
- method: "GET",
1832
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions`),
1833
- query: { limit: params.limit, offset: params.offset },
1834
- ...pickOverrides3(options)
1835
- });
1836
- return toPage(wire, toAgentVersion);
1837
- }
1838
- /** Yield every version of an agent, fetching pages as you go. */
1839
- async *listAllVersions(agentId, params = {}, options) {
1840
- const pageSize = params.limit ?? 50;
1841
- let offset = 0;
1842
- for (; ; ) {
1843
- const page = await this.listVersions(agentId, { limit: pageSize, offset }, options);
1844
- yield* page.data;
1845
- if (page.data.length === 0 || !page.hasMore) return;
1846
- offset += page.data.length;
1847
- }
1848
- }
1849
- /** Get one version of an agent by its number. */
1850
- async getVersion(agentId, versionNumber, options) {
1851
- const wire = await this.call({
1852
- method: "GET",
1853
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}`),
1854
- ...pickOverrides3(options)
1855
- });
1856
- return toAgentVersion(wire);
1857
- }
1858
- /**
1859
- * Roll back to an earlier version.
1860
- *
1861
- * This moves the agent's pointer; it does not cut a new version and nothing
1862
- * is lost.
1863
- */
1864
- async activateVersion(agentId, versionNumber, options) {
1865
- const wire = await this.call({
1866
- method: "POST",
1867
- path: runtimePath(
1868
- `/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}/activate`
1869
- ),
1870
- ...pickOverrides3(options)
1871
- });
1872
- return toAgent(wire);
1873
- }
1874
- };
1875
- var RunsClient = class extends BaseClient {
1876
- runBody(params, stream) {
1877
- return {
1878
- input: params.input,
1879
- end_user_id: params.endUserId,
1880
- session_id: params.sessionId,
1881
- max_turns: params.maxTurns,
1882
- stream
1883
- };
1884
- }
1885
- /** Retrying without a key can charge twice, so make one when retrying. */
1886
- idempotencyKey(params) {
1887
- if (params.idempotencyKey) return params.idempotencyKey;
1888
- return (params.maxRetries ?? 0) > 0 ? newIdempotencyKey() : void 0;
1889
- }
1890
- /**
1891
- * Run an agent and wait for the answer.
1892
- *
1893
- * @throws {@link BudgetExceededError} when the end user has spent their budget.
1894
- * @throws {@link SessionBusyError} when another run holds the session.
1895
- */
1896
- async create(agentId, params, options) {
1897
- const key = this.idempotencyKey(params);
1898
- const maxRetries = params.maxRetries ?? 0;
1899
- const headers = {
1900
- ...options?.headers ?? {},
1901
- ...key ? { "Idempotency-Key": key } : {}
1902
- };
1903
- for (let attempt = 0; ; attempt += 1) {
1904
- try {
1905
- const wire = await this.call({
1906
- method: "POST",
1907
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
1908
- body: this.runBody(params, false),
1909
- headers,
1910
- signal: options?.signal
1911
- });
1912
- return toRun(wire);
1913
- } catch (error) {
1914
- if (!(error instanceof SessionBusyError) || attempt >= maxRetries) throw error;
1915
- await sleep(
1916
- error.retryAfter !== void 0 ? error.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
1917
- );
1918
- }
1919
- }
1920
- }
1921
- /**
1922
- * Run an agent and watch it work.
1923
- *
1924
- * Yields events as the run happens: text as it is generated, each tool call
1925
- * and its result, what each generation cost, and finally `run.completed` or
1926
- * `run.failed`. Event names this SDK does not know are ignored, so a newer
1927
- * server cannot break an older client.
1928
- *
1929
- * A failed run arrives as a `run.failed` event, not a thrown error —
1930
- * including a run stopped mid-stream because the end user ran out of
1931
- * budget. Errors are thrown for runs that never started.
1932
- *
1933
- * A replay of an idempotency key omits `message.delta`: partial text is
1934
- * never stored, so there is nothing to replay.
1935
- *
1936
- * @example
1937
- * ```ts
1938
- * for await (const event of celesto.runs.stream(agent.id, {
1939
- * input: "Where is my order?",
1940
- * endUserId: "usr_8837",
1941
- * })) {
1942
- * if (event.name === "message.delta") process.stdout.write(event.data.text ?? "");
1943
- * }
1944
- * ```
1945
- */
1946
- async *stream(agentId, params, options) {
1947
- const key = this.idempotencyKey(params);
1948
- const maxRetries = params.maxRetries ?? 0;
1949
- const headers = {
1950
- Accept: "text/event-stream",
1951
- ...options?.headers ?? {},
1952
- ...key ? { "Idempotency-Key": key } : {}
1953
- };
1954
- for (let attempt = 0; ; attempt += 1) {
1955
- let response;
1956
- try {
1957
- response = await requestStream(buildRequestContext(this.config), {
1958
- method: "POST",
1959
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
1960
- body: this.runBody(params, true),
1961
- headers,
1962
- signal: options?.signal
1963
- });
1964
- } catch (error) {
1965
- const typed = toManagedAgentError(error);
1966
- if (!(typed instanceof SessionBusyError) || attempt >= maxRetries) throw typed;
1967
- await sleep(
1968
- typed.retryAfter !== void 0 ? typed.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
1969
- );
1970
- continue;
1971
- }
1972
- yield* readEventStream(response);
1973
- return;
1974
- }
1975
- }
1976
- /** Get a run by id, settled or not. */
1977
- async get(runId, options) {
1978
- const wire = await this.call({
1979
- method: "GET",
1980
- path: runtimePath(`/runs/${encodeURIComponent(runId)}`),
1981
- ...pickOverrides3(options)
1982
- });
1983
- return toRun(wire);
1984
- }
1985
- /**
1986
- * Read one page of a run's stored events.
1987
- *
1988
- * The same event contract as {@link stream}, read back after the fact,
1989
- * minus `message.delta` — partial text is never stored.
1990
- */
1991
- async listEvents(runId, params = {}, options) {
1992
- const wire = await this.call({
1993
- method: "GET",
1994
- path: runtimePath(`/runs/${encodeURIComponent(runId)}/events`),
1995
- query: { after_seq: params.afterSeq, limit: params.limit },
1996
- ...pickOverrides3(options)
1997
- });
1998
- return { data: wire.data ?? [], eventsVersion: wire.events_version };
1999
- }
2000
- /** Yield every stored event of a run, in order, fetching pages as you go. */
2001
- async *listAllEvents(runId, params = {}, options) {
2002
- const pageSize = params.limit ?? 100;
2003
- let afterSeq = params.afterSeq ?? 0;
2004
- for (; ; ) {
2005
- const page = await this.listEvents(runId, { afterSeq, limit: pageSize }, options);
2006
- yield* page.data;
2007
- if (page.data.length < pageSize) return;
2008
- const last = page.data[page.data.length - 1];
2009
- if (!last) return;
2010
- afterSeq = last.seq;
2011
- }
2012
- }
2013
- };
2014
- var SessionsClient = class extends BaseClient {
2015
- /** List one page of an end user's sessions. */
2016
- async list(params, options) {
2017
- const wire = await this.call({
2018
- method: "GET",
2019
- path: runtimePath("/sessions"),
2020
- query: {
2021
- end_user_id: params.endUserId,
2022
- limit: params.limit,
2023
- offset: params.offset
2024
- },
2025
- ...pickOverrides3(options)
2026
- });
2027
- return toPage(wire, toSession);
2028
- }
2029
- /** Yield every session for an end user, fetching pages as you go. */
2030
- async *listAll(params, options) {
2031
- const pageSize = params.limit ?? 50;
2032
- let offset = 0;
2033
- for (; ; ) {
2034
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
2035
- yield* page.data;
2036
- if (page.data.length === 0 || !page.hasMore) return;
2037
- offset += page.data.length;
2038
- }
2039
- }
2040
- /**
2041
- * Get a session and a page of its transcript.
2042
- *
2043
- * The transcript pages backwards: `beforeSeq` asks for what came before a
2044
- * message you already have.
2045
- */
2046
- async get(sessionId, params = {}, options) {
2047
- const wire = await this.call({
2048
- method: "GET",
2049
- path: runtimePath(`/sessions/${encodeURIComponent(sessionId)}`),
2050
- query: { limit: params.limit, before_seq: params.beforeSeq },
2051
- ...pickOverrides3(options)
2052
- });
2053
- return {
2054
- session: toSession(wire.session),
2055
- messages: (wire.messages ?? []).map(toSessionMessage)
2056
- };
2057
- }
2058
- /** Yield a session's messages newest first, fetching pages as you go. */
2059
- async *listAllMessages(sessionId, params = {}, options) {
2060
- const pageSize = params.limit ?? 50;
2061
- let beforeSeq = params.beforeSeq;
2062
- for (; ; ) {
2063
- const transcript = await this.get(sessionId, { limit: pageSize, beforeSeq }, options);
2064
- const messages = transcript.messages;
2065
- if (messages.length === 0) return;
2066
- yield* [...messages].sort((a, b) => b.seq - a.seq);
2067
- if (messages.length < pageSize) return;
2068
- beforeSeq = messages.reduce((lowest, m) => Math.min(lowest, m.seq), Infinity);
2069
- }
2070
- }
2071
- };
2072
- var EndUsersClient = class extends BaseClient {
2073
- /** Get an end user's budget and activity. */
2074
- async get(endUserId, options) {
2075
- const wire = await this.call({
2076
- method: "GET",
2077
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
2078
- ...pickOverrides3(options)
2079
- });
2080
- return toEndUser(wire);
2081
- }
2082
- /**
2083
- * Set an end user's budget override or metadata, creating them if needed.
2084
- *
2085
- * Fields you do not pass are left alone. Passing `null` clears the field:
2086
- * `budgetCapUsd: null` drops back to your organization's default budget.
2087
- */
2088
- async update(endUserId, params, options) {
2089
- const body = {};
2090
- if (params.budgetCapUsd !== void 0) {
2091
- body.budget_cap_usd = params.budgetCapUsd === null ? null : toMoneyString(params.budgetCapUsd);
2092
- }
2093
- if (params.metadata !== void 0) {
2094
- body.metadata = params.metadata;
2095
- }
2096
- const wire = await this.call({
2097
- method: "PUT",
2098
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
2099
- body,
2100
- ...pickOverrides3(options)
2101
- });
2102
- return toEndUser(wire);
2103
- }
2104
- /** Drop an end user's override, back to the organization default. */
2105
- async clearBudget(endUserId, options) {
2106
- return this.update(endUserId, { budgetCapUsd: null }, options);
2107
- }
2108
- };
2109
- var RuntimeSettingsClient = class extends BaseClient {
2110
- /** Read the default budget every end user starts with. */
2111
- async get(options) {
2112
- const wire = await this.call({
2113
- method: "GET",
2114
- path: runtimePath("/runtime/settings"),
2115
- ...pickOverrides3(options)
2116
- });
2117
- return toRuntimeSettings(wire);
2118
- }
2119
- /**
2120
- * Set the default budget every end user starts with.
2121
- *
2122
- * Pass `null` to remove the default, which leaves end users uncapped unless
2123
- * they have their own override.
2124
- */
2125
- async update(params, options) {
2126
- const body = {};
2127
- if (params.defaultEndUserBudgetUsd !== void 0) {
2128
- body.default_end_user_budget_usd = params.defaultEndUserBudgetUsd === null ? null : toMoneyString(params.defaultEndUserBudgetUsd);
2129
- }
2130
- const wire = await this.call({
2131
- method: "PUT",
2132
- path: runtimePath("/runtime/settings"),
2133
- body,
2134
- ...pickOverrides3(options)
2135
- });
2136
- return toRuntimeSettings(wire);
2137
- }
2138
- };
2139
- async function* readEventStream(response) {
2140
- if (!response.body) {
2141
- throw new Error("Celesto did not return a run event stream.");
2142
- }
2143
- const reader = response.body.getReader();
2144
- const textDecoder = new TextDecoder();
2145
- const sse = new SseDecoder();
2146
- let completed = false;
2147
- try {
2148
- for (; ; ) {
2149
- const chunk = await reader.read();
2150
- if (chunk.done) {
2151
- completed = true;
2152
- for (const frame of sse.push(textDecoder.decode())) {
2153
- const event = toRunEvent(frame);
2154
- if (event) yield event;
2155
- }
2156
- for (const frame of sse.flush()) {
2157
- const event = toRunEvent(frame);
2158
- if (event) yield event;
2159
- }
2160
- return;
2161
- }
2162
- for (const frame of sse.push(textDecoder.decode(chunk.value, { stream: true }))) {
2163
- const event = toRunEvent(frame);
2164
- if (event) yield event;
2165
- }
2166
- }
2167
- } finally {
2168
- if (!completed) {
2169
- try {
2170
- await reader.cancel();
2171
- } catch {
2172
- }
2173
- }
2174
- reader.releaseLock();
2175
- }
2176
- }
2177
- var ManagedAgentsClient = class {
2178
- constructor(config = {}) {
2179
- this.agents = new AgentsClient(config);
2180
- this.runs = new RunsClient(config);
2181
- this.sessions = new SessionsClient(config);
2182
- this.endUsers = new EndUsersClient(config);
2183
- this.settings = new RuntimeSettingsClient(config);
2184
- }
2185
- };
2186
829
  // Annotate the CommonJS export names for ESM import in node:
2187
830
  0 && (module.exports = {
2188
- ALLOWED_CONFIG_KEYS,
2189
- AgentArchivedError,
2190
- AgentsClient,
2191
- BudgetExceededError,
2192
831
  CelestoApiError,
2193
832
  CelestoError,
2194
833
  CelestoNetworkError,
2195
834
  Computer,
2196
- ConfigKeyNotAllowedError,
2197
- EVENTS_VERSION,
2198
- EndUsersClient,
2199
- GatekeeperClient,
2200
- IdempotencyConflictError,
2201
- KNOWN_EVENTS,
2202
835
  MISSING_CREDENTIALS_MESSAGE,
2203
- ManagedAgentError,
2204
- ManagedAgentsClient,
2205
- ModelRequiresOwnKeyError,
2206
- ProviderNotConnectedError,
2207
- RunsClient,
2208
- RuntimeSettingsClient,
2209
- SessionAgentMismatchError,
2210
- SessionBusyError,
2211
- SessionEndUserMismatchError,
2212
- SessionsClient,
2213
- eventText,
2214
- isTerminal,
2215
- parseRunEvents,
2216
- parseSseFrames,
2217
836
  resolveCelestoApiKey,
2218
- resolveClientConfig,
2219
- toRunEvent
837
+ resolveClientConfig
2220
838
  });
2221
839
  //# sourceMappingURL=index.cjs.map