@celestoai/sdk 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +130 -254
  3. package/dist/{chunk-52TE4RZV.js → chunk-3HEUI5UL.js} +341 -306
  4. package/dist/chunk-3HEUI5UL.js.map +1 -0
  5. package/dist/computers/index.cjs +211 -347
  6. package/dist/computers/index.cjs.map +1 -1
  7. package/dist/computers/index.d.cts +1 -239
  8. package/dist/computers/index.d.ts +1 -239
  9. package/dist/computers/index.js +1 -2
  10. package/dist/index-59d7VJXL.d.cts +303 -0
  11. package/dist/index-59d7VJXL.d.ts +303 -0
  12. package/dist/index.cjs +252 -1573
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +22 -4
  15. package/dist/index.d.ts +22 -4
  16. package/dist/index.js +5 -61
  17. package/package.json +25 -22
  18. package/dist/agents/index.cjs +0 -1226
  19. package/dist/agents/index.cjs.map +0 -1
  20. package/dist/agents/index.d.cts +0 -2
  21. package/dist/agents/index.d.ts +0 -2
  22. package/dist/agents/index.js +0 -60
  23. package/dist/agents/index.js.map +0 -1
  24. package/dist/chunk-52TE4RZV.js.map +0 -1
  25. package/dist/chunk-6Y2YZCPU.js +0 -1007
  26. package/dist/chunk-6Y2YZCPU.js.map +0 -1
  27. package/dist/chunk-P7F52CSQ.js +0 -177
  28. package/dist/chunk-P7F52CSQ.js.map +0 -1
  29. package/dist/chunk-THPVQCTE.js +0 -183
  30. package/dist/chunk-THPVQCTE.js.map +0 -1
  31. package/dist/config-dDPvsH-K.d.cts +0 -42
  32. package/dist/config-dDPvsH-K.d.ts +0 -42
  33. package/dist/gatekeeper/index.cjs +0 -348
  34. package/dist/gatekeeper/index.cjs.map +0 -1
  35. package/dist/gatekeeper/index.d.cts +0 -104
  36. package/dist/gatekeeper/index.d.ts +0 -104
  37. package/dist/gatekeeper/index.js +0 -8
  38. package/dist/gatekeeper/index.js.map +0 -1
  39. package/dist/index-Cii1_OFg.d.ts +0 -696
  40. package/dist/index-CsEA7qMF.d.cts +0 -696
@@ -1,1226 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/agents/index.ts
21
- var agents_exports = {};
22
- __export(agents_exports, {
23
- ALLOWED_CONFIG_KEYS: () => ALLOWED_CONFIG_KEYS,
24
- AgentArchivedError: () => AgentArchivedError,
25
- AgentsClient: () => AgentsClient,
26
- BudgetExceededError: () => BudgetExceededError,
27
- ConfigKeyNotAllowedError: () => ConfigKeyNotAllowedError,
28
- EVENTS_VERSION: () => EVENTS_VERSION,
29
- EVENTS_VERSION_HEADER: () => EVENTS_VERSION_HEADER,
30
- EndUsersClient: () => EndUsersClient,
31
- IdempotencyConflictError: () => IdempotencyConflictError,
32
- KNOWN_EVENTS: () => KNOWN_EVENTS,
33
- ManagedAgentError: () => ManagedAgentError,
34
- ManagedAgentsClient: () => ManagedAgentsClient,
35
- ModelRequiresOwnKeyError: () => ModelRequiresOwnKeyError,
36
- ProviderNotConnectedError: () => ProviderNotConnectedError,
37
- RunsClient: () => RunsClient,
38
- RuntimeSettingsClient: () => RuntimeSettingsClient,
39
- SessionAgentMismatchError: () => SessionAgentMismatchError,
40
- SessionBusyError: () => SessionBusyError,
41
- SessionEndUserMismatchError: () => SessionEndUserMismatchError,
42
- SessionsClient: () => SessionsClient,
43
- SseDecoder: () => SseDecoder,
44
- eventText: () => eventText,
45
- isTerminal: () => isTerminal,
46
- parseRunEvents: () => parseRunEvents,
47
- parseSseFrames: () => parseSseFrames,
48
- toManagedAgentError: () => toManagedAgentError,
49
- toRunEvent: () => toRunEvent
50
- });
51
- module.exports = __toCommonJS(agents_exports);
52
-
53
- // src/core/config.ts
54
- var DEFAULT_BASE_URL = "https://api.celesto.ai";
55
- var buildRequestContext = (config) => ({
56
- fetch: config.fetch ?? fetch,
57
- baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
58
- token: config.token ?? config.apiKey,
59
- organizationId: config.organizationId,
60
- userAgent: config.userAgent,
61
- timeoutMs: config.timeoutMs,
62
- headers: config.headers
63
- });
64
-
65
- // src/core/errors.ts
66
- var CelestoError = class extends Error {
67
- constructor(message) {
68
- super(message);
69
- this.name = "CelestoError";
70
- }
71
- };
72
- var CelestoApiError = class extends CelestoError {
73
- constructor(message, status, data, requestId, headers) {
74
- super(message);
75
- this.name = "CelestoApiError";
76
- this.status = status;
77
- this.data = data;
78
- this.requestId = requestId;
79
- this.headers = headers;
80
- }
81
- };
82
- var CelestoNetworkError = class extends CelestoError {
83
- constructor(message, cause) {
84
- super(message);
85
- this.name = "CelestoNetworkError";
86
- this.cause = cause;
87
- }
88
- };
89
-
90
- // src/core/http.ts
91
- var joinUrl = (baseUrl, path) => {
92
- const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
93
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
94
- return `${trimmedBase}${normalizedPath}`;
95
- };
96
- var buildQuery = (query) => {
97
- if (!query) {
98
- return "";
99
- }
100
- const params = new URLSearchParams();
101
- for (const [key, value] of Object.entries(query)) {
102
- if (value === void 0 || value === null) {
103
- continue;
104
- }
105
- if (Array.isArray(value)) {
106
- for (const item of value) {
107
- params.append(key, String(item));
108
- }
109
- continue;
110
- }
111
- params.set(key, String(value));
112
- }
113
- const serialized = params.toString();
114
- return serialized ? `?${serialized}` : "";
115
- };
116
- var parseResponseBody = async (response) => {
117
- if (response.status === 204) {
118
- return void 0;
119
- }
120
- const contentType = response.headers.get("content-type") ?? "";
121
- if (contentType.includes("application/json")) {
122
- return response.json();
123
- }
124
- return response.text();
125
- };
126
- var extractErrorMessage = (data, status) => {
127
- if (data && typeof data === "object") {
128
- const record = data;
129
- if (typeof record.detail === "string") {
130
- return record.detail;
131
- }
132
- if (typeof record.message === "string") {
133
- return record.message;
134
- }
135
- if (typeof record.error === "string") {
136
- return record.error;
137
- }
138
- }
139
- return `Request failed with status ${status}`;
140
- };
141
- var buildRequestInit = (ctx, options) => {
142
- const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
143
- const headers = {
144
- ...ctx.headers ?? {},
145
- ...options.headers ?? {}
146
- };
147
- if (ctx.token) {
148
- headers.Authorization = `Bearer ${ctx.token}`;
149
- }
150
- if (ctx.organizationId) {
151
- headers["X-Current-Organization"] = ctx.organizationId;
152
- }
153
- if (ctx.userAgent && !headers["User-Agent"]) {
154
- headers["User-Agent"] = ctx.userAgent;
155
- }
156
- const init = {
157
- method: options.method,
158
- headers,
159
- signal: options.signal
160
- };
161
- if (options.body !== void 0) {
162
- headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
163
- init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
164
- }
165
- return { url, init };
166
- };
167
- var request = async (ctx, options) => {
168
- const { url, init } = buildRequestInit(ctx, options);
169
- let timeoutId;
170
- let controller;
171
- if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
172
- controller = new AbortController();
173
- timeoutId = setTimeout(() => controller?.abort(), ctx.timeoutMs);
174
- init.signal = controller.signal;
175
- }
176
- try {
177
- const response = await ctx.fetch(url, init);
178
- const data = await parseResponseBody(response);
179
- if (!response.ok) {
180
- const message = extractErrorMessage(data, response.status);
181
- throw new CelestoApiError(
182
- message,
183
- response.status,
184
- data,
185
- response.headers.get("x-request-id") ?? void 0,
186
- response.headers
187
- );
188
- }
189
- return data;
190
- } catch (err) {
191
- if (err instanceof CelestoApiError) {
192
- throw err;
193
- }
194
- const error = err instanceof Error ? err : new Error(String(err));
195
- throw new CelestoNetworkError(error.message, error);
196
- } finally {
197
- if (timeoutId) {
198
- clearTimeout(timeoutId);
199
- }
200
- }
201
- };
202
- var requestStream = async (ctx, options) => {
203
- const { url, init } = buildRequestInit(ctx, options);
204
- try {
205
- const response = await ctx.fetch(url, init);
206
- if (!response.ok) {
207
- const data = await parseResponseBody(response);
208
- const message = extractErrorMessage(data, response.status);
209
- throw new CelestoApiError(
210
- message,
211
- response.status,
212
- data,
213
- response.headers.get("x-request-id") ?? void 0,
214
- response.headers
215
- );
216
- }
217
- return response;
218
- } catch (err) {
219
- if (err instanceof CelestoApiError) {
220
- throw err;
221
- }
222
- const error = err instanceof Error ? err : new Error(String(err));
223
- throw new CelestoNetworkError(error.message, error);
224
- }
225
- };
226
-
227
- // src/agents/errors.ts
228
- var ManagedAgentError = class extends CelestoApiError {
229
- constructor(message, status, data, options = {}) {
230
- super(message, status, data, options.requestId, options.headers);
231
- /** True when retrying the identical request can succeed. */
232
- this.retryable = false;
233
- this.name = "ManagedAgentError";
234
- this.code = options.code;
235
- this.retryAfter = options.retryAfter;
236
- }
237
- };
238
- var BudgetExceededError = class extends ManagedAgentError {
239
- constructor(...args) {
240
- super(...args);
241
- this.name = "BudgetExceededError";
242
- }
243
- };
244
- var SessionBusyError = class extends ManagedAgentError {
245
- constructor(...args) {
246
- super(...args);
247
- this.retryable = true;
248
- this.name = "SessionBusyError";
249
- }
250
- };
251
- var IdempotencyConflictError = class extends ManagedAgentError {
252
- constructor(...args) {
253
- super(...args);
254
- this.name = "IdempotencyConflictError";
255
- }
256
- };
257
- var AgentArchivedError = class extends ManagedAgentError {
258
- constructor(...args) {
259
- super(...args);
260
- this.name = "AgentArchivedError";
261
- }
262
- };
263
- var ProviderNotConnectedError = class extends ManagedAgentError {
264
- constructor(...args) {
265
- super(...args);
266
- this.name = "ProviderNotConnectedError";
267
- }
268
- };
269
- var SessionAgentMismatchError = class extends ManagedAgentError {
270
- constructor(...args) {
271
- super(...args);
272
- this.name = "SessionAgentMismatchError";
273
- }
274
- };
275
- var SessionEndUserMismatchError = class extends ManagedAgentError {
276
- constructor(...args) {
277
- super(...args);
278
- this.name = "SessionEndUserMismatchError";
279
- }
280
- };
281
- var ModelRequiresOwnKeyError = class extends ManagedAgentError {
282
- constructor(...args) {
283
- super(...args);
284
- this.name = "ModelRequiresOwnKeyError";
285
- }
286
- };
287
- var ConfigKeyNotAllowedError = class extends ManagedAgentError {
288
- constructor(...args) {
289
- super(...args);
290
- this.name = "ConfigKeyNotAllowedError";
291
- }
292
- };
293
- var ERROR_CLASSES = {
294
- budget_exceeded: BudgetExceededError,
295
- session_busy: SessionBusyError,
296
- idempotency_conflict: IdempotencyConflictError,
297
- agent_archived: AgentArchivedError,
298
- provider_not_connected: ProviderNotConnectedError,
299
- session_agent_mismatch: SessionAgentMismatchError,
300
- session_end_user_mismatch: SessionEndUserMismatchError,
301
- model_requires_own_key: ModelRequiresOwnKeyError,
302
- config_key_not_allowed: ConfigKeyNotAllowedError
303
- };
304
- var STATUS_FALLBACK = {
305
- 402: BudgetExceededError
306
- };
307
- var readErrorCode = (data) => {
308
- if (!data || typeof data !== "object") return void 0;
309
- const record = data;
310
- const detail = record.detail;
311
- const raw = detail && typeof detail === "object" ? detail.code : record.code;
312
- if (typeof raw !== "string") return void 0;
313
- return raw in ERROR_CLASSES ? raw : void 0;
314
- };
315
- var readMessage = (data, fallback) => {
316
- if (data && typeof data === "object") {
317
- const detail = data.detail;
318
- if (detail && typeof detail === "object") {
319
- const message = detail.message;
320
- if (typeof message === "string") return message;
321
- }
322
- }
323
- return fallback;
324
- };
325
- var readRetryAfter = (headers) => {
326
- const raw = headers?.get("retry-after");
327
- if (!raw) return void 0;
328
- const seconds = Number(raw);
329
- return Number.isFinite(seconds) ? seconds : void 0;
330
- };
331
- var toManagedAgentError = (error) => {
332
- if (!(error instanceof CelestoApiError) || error instanceof ManagedAgentError) {
333
- return error;
334
- }
335
- const code = readErrorCode(error.data);
336
- const ErrorClass = (code && ERROR_CLASSES[code]) ?? STATUS_FALLBACK[error.status];
337
- if (!ErrorClass) return error;
338
- return new ErrorClass(readMessage(error.data, error.message), error.status, error.data, {
339
- code: code ?? (error.status === 402 ? "budget_exceeded" : void 0),
340
- retryAfter: readRetryAfter(error.headers),
341
- requestId: error.requestId,
342
- headers: error.headers
343
- });
344
- };
345
-
346
- // src/agents/events.ts
347
- var EVENTS_VERSION = "1";
348
- var EVENTS_VERSION_HEADER = "X-Celesto-Events-Version";
349
- var KNOWN_EVENTS = [
350
- "run.started",
351
- "message.delta",
352
- "message.completed",
353
- "tool.call",
354
- "tool.result",
355
- "usage",
356
- "run.completed",
357
- "run.failed"
358
- ];
359
- var KNOWN_EVENT_SET = new Set(KNOWN_EVENTS);
360
- var asRecord = (value) => value && typeof value === "object" ? value : {};
361
- var str = (value) => typeof value === "string" ? value : null;
362
- var num = (value) => typeof value === "number" ? value : null;
363
- var int = (value) => typeof value === "number" ? value : 0;
364
- var money = (value) => typeof value === "string" ? value : "0.000000";
365
- var toUsage = (value) => {
366
- const raw = asRecord(value);
367
- return {
368
- inputTokens: int(raw.input_tokens),
369
- outputTokens: int(raw.output_tokens),
370
- totalTokens: int(raw.total_tokens),
371
- costUsd: money(raw.cost_usd)
372
- };
373
- };
374
- var toToolResultData = (raw) => {
375
- const data = {
376
- callId: str(raw.call_id),
377
- name: str(raw.name),
378
- turn: num(raw.turn)
379
- };
380
- if ("error" in raw) {
381
- data.error = raw.error;
382
- } else {
383
- data.result = raw.result;
384
- }
385
- return data;
386
- };
387
- var toRunEvent = (frame) => {
388
- const name = frame.event;
389
- if (!name || !KNOWN_EVENT_SET.has(name)) return void 0;
390
- let parsed;
391
- try {
392
- parsed = frame.data ? JSON.parse(frame.data) : {};
393
- } catch {
394
- return void 0;
395
- }
396
- const raw = asRecord(parsed);
397
- const seq = frame.id !== void 0 && frame.id !== "" ? Number(frame.id) : NaN;
398
- const position = Number.isFinite(seq) ? seq : null;
399
- switch (name) {
400
- case "run.started":
401
- return {
402
- name: "run.started",
403
- seq: position,
404
- data: {
405
- runId: str(raw.run_id) ?? "",
406
- agentId: str(raw.agent_id) ?? "",
407
- agentVersionId: str(raw.agent_version_id) ?? "",
408
- sessionId: str(raw.session_id) ?? "",
409
- endUserId: str(raw.end_user_id) ?? "",
410
- model: str(raw.model) ?? "",
411
- createdAt: str(raw.created_at) ?? ""
412
- }
413
- };
414
- case "message.delta":
415
- return {
416
- name: "message.delta",
417
- seq: position,
418
- data: { text: str(raw.text), turn: num(raw.turn) }
419
- };
420
- case "message.completed":
421
- return {
422
- name: "message.completed",
423
- seq: position,
424
- data: { text: str(raw.text), turn: num(raw.turn) }
425
- };
426
- case "tool.call":
427
- return {
428
- name: "tool.call",
429
- seq: position,
430
- data: {
431
- callId: str(raw.call_id),
432
- name: str(raw.name),
433
- args: raw.args,
434
- turn: num(raw.turn)
435
- }
436
- };
437
- case "tool.result":
438
- return { name: "tool.result", seq: position, data: toToolResultData(raw) };
439
- case "usage":
440
- return {
441
- name: "usage",
442
- seq: position,
443
- data: {
444
- turn: num(raw.turn),
445
- model: str(raw.model),
446
- inputTokens: int(raw.input_tokens),
447
- outputTokens: int(raw.output_tokens),
448
- totalTokens: int(raw.total_tokens),
449
- costUsd: money(raw.cost_usd)
450
- }
451
- };
452
- case "run.completed":
453
- return {
454
- name: "run.completed",
455
- seq: position,
456
- data: {
457
- runId: str(raw.run_id) ?? "",
458
- status: str(raw.status) ?? "completed",
459
- output: str(raw.output),
460
- turnCount: num(raw.turn_count),
461
- usage: toUsage(raw.usage)
462
- }
463
- };
464
- case "run.failed":
465
- return {
466
- name: "run.failed",
467
- seq: position,
468
- data: {
469
- runId: str(raw.run_id) ?? "",
470
- status: str(raw.status) ?? "failed",
471
- errorCode: str(raw.error_code),
472
- error: str(raw.error),
473
- turnCount: num(raw.turn_count),
474
- usage: toUsage(raw.usage)
475
- }
476
- };
477
- default:
478
- return void 0;
479
- }
480
- };
481
- var isTerminal = (event) => event.name === "run.completed" || event.name === "run.failed";
482
- var eventText = (event) => {
483
- switch (event.name) {
484
- case "message.delta":
485
- case "message.completed":
486
- return event.data.text ?? "";
487
- case "run.completed":
488
- return event.data.output ?? "";
489
- default:
490
- return "";
491
- }
492
- };
493
- var SseDecoder = class {
494
- constructor() {
495
- this.buffer = "";
496
- }
497
- push(chunk) {
498
- this.buffer += chunk;
499
- const frames = [];
500
- let boundary = this.findBoundary();
501
- while (boundary) {
502
- const block = this.buffer.slice(0, boundary.index);
503
- this.buffer = this.buffer.slice(boundary.index + boundary.length);
504
- const frame = parseFrame(block);
505
- if (frame) frames.push(frame);
506
- boundary = this.findBoundary();
507
- }
508
- return frames;
509
- }
510
- /** Anything left in the buffer when the stream ends. */
511
- flush() {
512
- const block = this.buffer;
513
- this.buffer = "";
514
- const frame = parseFrame(block);
515
- return frame ? [frame] : [];
516
- }
517
- findBoundary() {
518
- const lf = this.buffer.indexOf("\n\n");
519
- const crlf = this.buffer.indexOf("\r\n\r\n");
520
- if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
521
- if (lf !== -1) return { index: lf, length: 2 };
522
- return void 0;
523
- }
524
- };
525
- var parseFrame = (block) => {
526
- let event;
527
- let id;
528
- const dataLines = [];
529
- let sawField = false;
530
- for (const rawLine of block.split("\n")) {
531
- const line = rawLine.replace(/\r$/, "");
532
- if (line === "" || line.startsWith(":")) continue;
533
- const separator = line.indexOf(":");
534
- const field = separator === -1 ? line : line.slice(0, separator);
535
- let value = separator === -1 ? "" : line.slice(separator + 1);
536
- if (value.startsWith(" ")) value = value.slice(1);
537
- if (field === "event") {
538
- event = value;
539
- sawField = true;
540
- } else if (field === "data") {
541
- dataLines.push(value);
542
- sawField = true;
543
- } else if (field === "id") {
544
- id = value;
545
- sawField = true;
546
- }
547
- }
548
- if (!sawField) return void 0;
549
- const frame = { data: dataLines.join("\n") };
550
- if (event !== void 0) frame.event = event;
551
- if (id !== void 0) frame.id = id;
552
- return frame;
553
- };
554
- var parseSseFrames = (body) => {
555
- const decoder = new SseDecoder();
556
- return [...decoder.push(body), ...decoder.flush()];
557
- };
558
- var parseRunEvents = (body) => {
559
- const events = [];
560
- for (const frame of parseSseFrames(body)) {
561
- const event = toRunEvent(frame);
562
- if (event) events.push(event);
563
- }
564
- return events;
565
- };
566
-
567
- // src/agents/client.ts
568
- var runtimePath = (path) => `/v1${path}`;
569
- var pickOverrides = (options) => ({
570
- headers: options?.headers,
571
- signal: options?.signal
572
- });
573
- var DEFAULT_RETRY_BACKOFF_MS = 1e3;
574
- var CONFIG_KEYS = {
575
- temperature: "temperature",
576
- topP: "top_p",
577
- maxTokens: "max_tokens",
578
- maxOutputTokens: "max_output_tokens",
579
- frequencyPenalty: "frequency_penalty",
580
- presencePenalty: "presence_penalty",
581
- seed: "seed",
582
- stop: "stop",
583
- reasoningEffort: "reasoning_effort",
584
- verbosity: "verbosity",
585
- maxTurns: "max_turns"
586
- };
587
- var ALLOWED_CONFIG_KEYS = Object.keys(CONFIG_KEYS);
588
- var WIRE_TO_CONFIG_KEY = new Map(
589
- Object.entries(CONFIG_KEYS).map(([key, wire]) => [
590
- wire,
591
- key
592
- ])
593
- );
594
- var toConfigWire = (config) => {
595
- if (!config) return void 0;
596
- const wire = {};
597
- const unknown = [];
598
- for (const [key, value] of Object.entries(config)) {
599
- if (value === void 0) continue;
600
- const wireKey = CONFIG_KEYS[key];
601
- if (!wireKey) {
602
- unknown.push(key);
603
- continue;
604
- }
605
- wire[wireKey] = value;
606
- }
607
- if (unknown.length > 0) {
608
- throw new ConfigKeyNotAllowedError(
609
- `Agent config does not accept ${unknown.join(", ")}. It accepts only: ${ALLOWED_CONFIG_KEYS.join(", ")}.`,
610
- 422,
611
- void 0,
612
- { code: "config_key_not_allowed" }
613
- );
614
- }
615
- return wire;
616
- };
617
- var toConfig = (wire) => {
618
- if (!wire || typeof wire !== "object") return null;
619
- const config = {};
620
- for (const [wireKey, value] of Object.entries(wire)) {
621
- const key = WIRE_TO_CONFIG_KEY.get(wireKey);
622
- config[key ?? wireKey] = value;
623
- }
624
- return config;
625
- };
626
- var toAgent = (wire) => ({
627
- id: wire.id,
628
- object: wire.object ?? "agent",
629
- name: wire.name,
630
- description: wire.description ?? null,
631
- model: wire.model,
632
- instructions: wire.instructions ?? null,
633
- config: toConfig(wire.config),
634
- version: wire.version,
635
- currentVersionId: wire.current_version_id,
636
- projectId: wire.project_id,
637
- organizationId: wire.organization_id,
638
- status: wire.status,
639
- createdAt: wire.created_at,
640
- updatedAt: wire.updated_at
641
- });
642
- var toAgentVersion = (wire) => ({
643
- id: wire.id,
644
- object: wire.object ?? "agent_version",
645
- agentId: wire.agent_id,
646
- version: wire.version,
647
- name: wire.name,
648
- description: wire.description ?? null,
649
- model: wire.model,
650
- instructions: wire.instructions ?? null,
651
- config: toConfig(wire.config),
652
- createdAt: wire.created_at
653
- });
654
- var toUsage2 = (wire) => ({
655
- inputTokens: wire.input_tokens,
656
- outputTokens: wire.output_tokens,
657
- totalTokens: wire.total_tokens,
658
- // Money stays a string. Never parseFloat this.
659
- costUsd: wire.cost_usd
660
- });
661
- var toRun = (wire) => ({
662
- runId: wire.run_id,
663
- object: wire.object ?? "run",
664
- status: wire.status,
665
- errorCode: wire.error_code ?? null,
666
- error: wire.error ?? null,
667
- output: wire.output ?? null,
668
- usage: toUsage2(wire.usage),
669
- agentId: wire.agent_id,
670
- agentVersionId: wire.agent_version_id,
671
- sessionId: wire.session_id,
672
- endUserId: wire.end_user_id,
673
- turnCount: wire.turn_count ?? null,
674
- createdAt: wire.created_at,
675
- startedAt: wire.started_at ?? null,
676
- endedAt: wire.ended_at ?? null
677
- });
678
- var toSession = (wire) => ({
679
- id: wire.id,
680
- object: wire.object ?? "session",
681
- agentId: wire.agent_id ?? null,
682
- endUserId: wire.end_user_id,
683
- status: wire.status,
684
- messageCount: wire.message_count,
685
- lastMessageAt: wire.last_message_at ?? null,
686
- createdAt: wire.created_at
687
- });
688
- var toSessionMessage = (wire) => ({
689
- seq: wire.seq,
690
- role: wire.role ?? null,
691
- item: wire.item,
692
- createdAt: wire.created_at
693
- });
694
- var toBudget = (wire) => ({
695
- capUsd: wire.cap_usd ?? null,
696
- source: wire.source,
697
- windowStart: wire.window_start,
698
- windowResetsAt: wire.window_resets_at,
699
- spentUsd: wire.spent_usd,
700
- remainingUsd: wire.remaining_usd ?? null
701
- });
702
- var toEndUser = (wire) => ({
703
- endUserId: wire.end_user_id,
704
- object: wire.object ?? "end_user",
705
- firstActivityAt: wire.first_activity_at,
706
- budget: toBudget(wire.budget),
707
- metadata: wire.metadata ?? null,
708
- createdAt: wire.created_at
709
- });
710
- var toRuntimeSettings = (wire) => ({
711
- organizationId: wire.organization_id,
712
- defaultEndUserBudgetUsd: wire.default_end_user_budget_usd ?? null
713
- });
714
- var toPage = (wire, map) => ({
715
- data: (wire.data ?? []).map(map),
716
- hasMore: wire.has_more ?? false
717
- });
718
- var MONEY_PATTERN = /^\d{1,8}(\.\d{1,6})?$/;
719
- var toMoneyString = (value) => {
720
- if (typeof value === "number") {
721
- throw new TypeError(
722
- `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.`
723
- );
724
- }
725
- const text = value.trim();
726
- if (!MONEY_PATTERN.test(text)) {
727
- throw new TypeError(
728
- `"${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.`
729
- );
730
- }
731
- return text;
732
- };
733
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
734
- var newIdempotencyKey = () => {
735
- const uuid = globalThis.crypto?.randomUUID?.();
736
- return uuid ?? `idem_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
737
- };
738
- var BaseClient = class {
739
- constructor(config) {
740
- this.config = config;
741
- }
742
- /** Every call goes through here, so refusals arrive already typed. */
743
- async call(options) {
744
- try {
745
- return await request(buildRequestContext(this.config), options);
746
- } catch (error) {
747
- throw toManagedAgentError(error);
748
- }
749
- }
750
- };
751
- var AgentsClient = class extends BaseClient {
752
- /** Create an agent, at version 1. */
753
- async create(params, options) {
754
- const wire = await this.call({
755
- method: "POST",
756
- path: runtimePath("/agents"),
757
- body: {
758
- name: params.name,
759
- model: params.model,
760
- instructions: params.instructions,
761
- description: params.description,
762
- config: toConfigWire(params.config),
763
- project_id: params.projectId
764
- },
765
- ...pickOverrides(options)
766
- });
767
- return toAgent(wire);
768
- }
769
- /** List one page of agents. Check `hasMore`; there is no total count. */
770
- async list(params = {}, options) {
771
- const wire = await this.call({
772
- method: "GET",
773
- path: runtimePath("/agents"),
774
- query: {
775
- project_id: params.projectId,
776
- include_archived: params.includeArchived,
777
- limit: params.limit,
778
- offset: params.offset
779
- },
780
- ...pickOverrides(options)
781
- });
782
- return toPage(wire, toAgent);
783
- }
784
- /** Yield every agent, fetching pages as you go. */
785
- async *listAll(params = {}, options) {
786
- const pageSize = params.limit ?? 50;
787
- let offset = 0;
788
- for (; ; ) {
789
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
790
- yield* page.data;
791
- if (page.data.length === 0 || !page.hasMore) return;
792
- offset += page.data.length;
793
- }
794
- }
795
- /** Get an agent, at its current version. */
796
- async get(agentId, options) {
797
- const wire = await this.call({
798
- method: "GET",
799
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
800
- ...pickOverrides(options)
801
- });
802
- return toAgent(wire);
803
- }
804
- /**
805
- * Replace an agent's definition, which cuts a new version.
806
- *
807
- * This is a full replacement, not a patch: whatever you leave out is
808
- * cleared. Read the agent first if you only mean to change one field.
809
- */
810
- async update(agentId, params, options) {
811
- const wire = await this.call({
812
- method: "PUT",
813
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
814
- body: {
815
- name: params.name,
816
- model: params.model,
817
- instructions: params.instructions,
818
- description: params.description,
819
- config: toConfigWire(params.config)
820
- },
821
- ...pickOverrides(options)
822
- });
823
- return toAgent(wire);
824
- }
825
- /**
826
- * Archive an agent. Archived agents refuse new runs.
827
- *
828
- * Past runs, versions, and transcripts stay readable.
829
- */
830
- async archive(agentId, options) {
831
- const wire = await this.call({
832
- method: "DELETE",
833
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
834
- ...pickOverrides(options)
835
- });
836
- return { id: wire.id, status: wire.status };
837
- }
838
- /** List one page of an agent's versions. */
839
- async listVersions(agentId, params = {}, options) {
840
- const wire = await this.call({
841
- method: "GET",
842
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions`),
843
- query: { limit: params.limit, offset: params.offset },
844
- ...pickOverrides(options)
845
- });
846
- return toPage(wire, toAgentVersion);
847
- }
848
- /** Yield every version of an agent, fetching pages as you go. */
849
- async *listAllVersions(agentId, params = {}, options) {
850
- const pageSize = params.limit ?? 50;
851
- let offset = 0;
852
- for (; ; ) {
853
- const page = await this.listVersions(agentId, { limit: pageSize, offset }, options);
854
- yield* page.data;
855
- if (page.data.length === 0 || !page.hasMore) return;
856
- offset += page.data.length;
857
- }
858
- }
859
- /** Get one version of an agent by its number. */
860
- async getVersion(agentId, versionNumber, options) {
861
- const wire = await this.call({
862
- method: "GET",
863
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}`),
864
- ...pickOverrides(options)
865
- });
866
- return toAgentVersion(wire);
867
- }
868
- /**
869
- * Roll back to an earlier version.
870
- *
871
- * This moves the agent's pointer; it does not cut a new version and nothing
872
- * is lost.
873
- */
874
- async activateVersion(agentId, versionNumber, options) {
875
- const wire = await this.call({
876
- method: "POST",
877
- path: runtimePath(
878
- `/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}/activate`
879
- ),
880
- ...pickOverrides(options)
881
- });
882
- return toAgent(wire);
883
- }
884
- };
885
- var RunsClient = class extends BaseClient {
886
- runBody(params, stream) {
887
- return {
888
- input: params.input,
889
- end_user_id: params.endUserId,
890
- session_id: params.sessionId,
891
- max_turns: params.maxTurns,
892
- stream
893
- };
894
- }
895
- /** Retrying without a key can charge twice, so make one when retrying. */
896
- idempotencyKey(params) {
897
- if (params.idempotencyKey) return params.idempotencyKey;
898
- return (params.maxRetries ?? 0) > 0 ? newIdempotencyKey() : void 0;
899
- }
900
- /**
901
- * Run an agent and wait for the answer.
902
- *
903
- * @throws {@link BudgetExceededError} when the end user has spent their budget.
904
- * @throws {@link SessionBusyError} when another run holds the session.
905
- */
906
- async create(agentId, params, options) {
907
- const key = this.idempotencyKey(params);
908
- const maxRetries = params.maxRetries ?? 0;
909
- const headers = {
910
- ...options?.headers ?? {},
911
- ...key ? { "Idempotency-Key": key } : {}
912
- };
913
- for (let attempt = 0; ; attempt += 1) {
914
- try {
915
- const wire = await this.call({
916
- method: "POST",
917
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
918
- body: this.runBody(params, false),
919
- headers,
920
- signal: options?.signal
921
- });
922
- return toRun(wire);
923
- } catch (error) {
924
- if (!(error instanceof SessionBusyError) || attempt >= maxRetries) throw error;
925
- await sleep(
926
- error.retryAfter !== void 0 ? error.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
927
- );
928
- }
929
- }
930
- }
931
- /**
932
- * Run an agent and watch it work.
933
- *
934
- * Yields events as the run happens: text as it is generated, each tool call
935
- * and its result, what each generation cost, and finally `run.completed` or
936
- * `run.failed`. Event names this SDK does not know are ignored, so a newer
937
- * server cannot break an older client.
938
- *
939
- * A failed run arrives as a `run.failed` event, not a thrown error —
940
- * including a run stopped mid-stream because the end user ran out of
941
- * budget. Errors are thrown for runs that never started.
942
- *
943
- * A replay of an idempotency key omits `message.delta`: partial text is
944
- * never stored, so there is nothing to replay.
945
- *
946
- * @example
947
- * ```ts
948
- * for await (const event of celesto.runs.stream(agent.id, {
949
- * input: "Where is my order?",
950
- * endUserId: "usr_8837",
951
- * })) {
952
- * if (event.name === "message.delta") process.stdout.write(event.data.text ?? "");
953
- * }
954
- * ```
955
- */
956
- async *stream(agentId, params, options) {
957
- const key = this.idempotencyKey(params);
958
- const maxRetries = params.maxRetries ?? 0;
959
- const headers = {
960
- Accept: "text/event-stream",
961
- ...options?.headers ?? {},
962
- ...key ? { "Idempotency-Key": key } : {}
963
- };
964
- for (let attempt = 0; ; attempt += 1) {
965
- let response;
966
- try {
967
- response = await requestStream(buildRequestContext(this.config), {
968
- method: "POST",
969
- path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
970
- body: this.runBody(params, true),
971
- headers,
972
- signal: options?.signal
973
- });
974
- } catch (error) {
975
- const typed = toManagedAgentError(error);
976
- if (!(typed instanceof SessionBusyError) || attempt >= maxRetries) throw typed;
977
- await sleep(
978
- typed.retryAfter !== void 0 ? typed.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
979
- );
980
- continue;
981
- }
982
- yield* readEventStream(response);
983
- return;
984
- }
985
- }
986
- /** Get a run by id, settled or not. */
987
- async get(runId, options) {
988
- const wire = await this.call({
989
- method: "GET",
990
- path: runtimePath(`/runs/${encodeURIComponent(runId)}`),
991
- ...pickOverrides(options)
992
- });
993
- return toRun(wire);
994
- }
995
- /**
996
- * Read one page of a run's stored events.
997
- *
998
- * The same event contract as {@link stream}, read back after the fact,
999
- * minus `message.delta` — partial text is never stored.
1000
- */
1001
- async listEvents(runId, params = {}, options) {
1002
- const wire = await this.call({
1003
- method: "GET",
1004
- path: runtimePath(`/runs/${encodeURIComponent(runId)}/events`),
1005
- query: { after_seq: params.afterSeq, limit: params.limit },
1006
- ...pickOverrides(options)
1007
- });
1008
- return { data: wire.data ?? [], eventsVersion: wire.events_version };
1009
- }
1010
- /** Yield every stored event of a run, in order, fetching pages as you go. */
1011
- async *listAllEvents(runId, params = {}, options) {
1012
- const pageSize = params.limit ?? 100;
1013
- let afterSeq = params.afterSeq ?? 0;
1014
- for (; ; ) {
1015
- const page = await this.listEvents(runId, { afterSeq, limit: pageSize }, options);
1016
- yield* page.data;
1017
- if (page.data.length < pageSize) return;
1018
- const last = page.data[page.data.length - 1];
1019
- if (!last) return;
1020
- afterSeq = last.seq;
1021
- }
1022
- }
1023
- };
1024
- var SessionsClient = class extends BaseClient {
1025
- /** List one page of an end user's sessions. */
1026
- async list(params, options) {
1027
- const wire = await this.call({
1028
- method: "GET",
1029
- path: runtimePath("/sessions"),
1030
- query: {
1031
- end_user_id: params.endUserId,
1032
- limit: params.limit,
1033
- offset: params.offset
1034
- },
1035
- ...pickOverrides(options)
1036
- });
1037
- return toPage(wire, toSession);
1038
- }
1039
- /** Yield every session for an end user, fetching pages as you go. */
1040
- async *listAll(params, options) {
1041
- const pageSize = params.limit ?? 50;
1042
- let offset = 0;
1043
- for (; ; ) {
1044
- const page = await this.list({ ...params, limit: pageSize, offset }, options);
1045
- yield* page.data;
1046
- if (page.data.length === 0 || !page.hasMore) return;
1047
- offset += page.data.length;
1048
- }
1049
- }
1050
- /**
1051
- * Get a session and a page of its transcript.
1052
- *
1053
- * The transcript pages backwards: `beforeSeq` asks for what came before a
1054
- * message you already have.
1055
- */
1056
- async get(sessionId, params = {}, options) {
1057
- const wire = await this.call({
1058
- method: "GET",
1059
- path: runtimePath(`/sessions/${encodeURIComponent(sessionId)}`),
1060
- query: { limit: params.limit, before_seq: params.beforeSeq },
1061
- ...pickOverrides(options)
1062
- });
1063
- return {
1064
- session: toSession(wire.session),
1065
- messages: (wire.messages ?? []).map(toSessionMessage)
1066
- };
1067
- }
1068
- /** Yield a session's messages newest first, fetching pages as you go. */
1069
- async *listAllMessages(sessionId, params = {}, options) {
1070
- const pageSize = params.limit ?? 50;
1071
- let beforeSeq = params.beforeSeq;
1072
- for (; ; ) {
1073
- const transcript = await this.get(sessionId, { limit: pageSize, beforeSeq }, options);
1074
- const messages = transcript.messages;
1075
- if (messages.length === 0) return;
1076
- yield* [...messages].sort((a, b) => b.seq - a.seq);
1077
- if (messages.length < pageSize) return;
1078
- beforeSeq = messages.reduce((lowest, m) => Math.min(lowest, m.seq), Infinity);
1079
- }
1080
- }
1081
- };
1082
- var EndUsersClient = class extends BaseClient {
1083
- /** Get an end user's budget and activity. */
1084
- async get(endUserId, options) {
1085
- const wire = await this.call({
1086
- method: "GET",
1087
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
1088
- ...pickOverrides(options)
1089
- });
1090
- return toEndUser(wire);
1091
- }
1092
- /**
1093
- * Set an end user's budget override or metadata, creating them if needed.
1094
- *
1095
- * Fields you do not pass are left alone. Passing `null` clears the field:
1096
- * `budgetCapUsd: null` drops back to your organization's default budget.
1097
- */
1098
- async update(endUserId, params, options) {
1099
- const body = {};
1100
- if (params.budgetCapUsd !== void 0) {
1101
- body.budget_cap_usd = params.budgetCapUsd === null ? null : toMoneyString(params.budgetCapUsd);
1102
- }
1103
- if (params.metadata !== void 0) {
1104
- body.metadata = params.metadata;
1105
- }
1106
- const wire = await this.call({
1107
- method: "PUT",
1108
- path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
1109
- body,
1110
- ...pickOverrides(options)
1111
- });
1112
- return toEndUser(wire);
1113
- }
1114
- /** Drop an end user's override, back to the organization default. */
1115
- async clearBudget(endUserId, options) {
1116
- return this.update(endUserId, { budgetCapUsd: null }, options);
1117
- }
1118
- };
1119
- var RuntimeSettingsClient = class extends BaseClient {
1120
- /** Read the default budget every end user starts with. */
1121
- async get(options) {
1122
- const wire = await this.call({
1123
- method: "GET",
1124
- path: runtimePath("/runtime/settings"),
1125
- ...pickOverrides(options)
1126
- });
1127
- return toRuntimeSettings(wire);
1128
- }
1129
- /**
1130
- * Set the default budget every end user starts with.
1131
- *
1132
- * Pass `null` to remove the default, which leaves end users uncapped unless
1133
- * they have their own override.
1134
- */
1135
- async update(params, options) {
1136
- const body = {};
1137
- if (params.defaultEndUserBudgetUsd !== void 0) {
1138
- body.default_end_user_budget_usd = params.defaultEndUserBudgetUsd === null ? null : toMoneyString(params.defaultEndUserBudgetUsd);
1139
- }
1140
- const wire = await this.call({
1141
- method: "PUT",
1142
- path: runtimePath("/runtime/settings"),
1143
- body,
1144
- ...pickOverrides(options)
1145
- });
1146
- return toRuntimeSettings(wire);
1147
- }
1148
- };
1149
- async function* readEventStream(response) {
1150
- if (!response.body) {
1151
- throw new Error("Celesto did not return a run event stream.");
1152
- }
1153
- const reader = response.body.getReader();
1154
- const textDecoder = new TextDecoder();
1155
- const sse = new SseDecoder();
1156
- let completed = false;
1157
- try {
1158
- for (; ; ) {
1159
- const chunk = await reader.read();
1160
- if (chunk.done) {
1161
- completed = true;
1162
- for (const frame of sse.push(textDecoder.decode())) {
1163
- const event = toRunEvent(frame);
1164
- if (event) yield event;
1165
- }
1166
- for (const frame of sse.flush()) {
1167
- const event = toRunEvent(frame);
1168
- if (event) yield event;
1169
- }
1170
- return;
1171
- }
1172
- for (const frame of sse.push(textDecoder.decode(chunk.value, { stream: true }))) {
1173
- const event = toRunEvent(frame);
1174
- if (event) yield event;
1175
- }
1176
- }
1177
- } finally {
1178
- if (!completed) {
1179
- try {
1180
- await reader.cancel();
1181
- } catch {
1182
- }
1183
- }
1184
- reader.releaseLock();
1185
- }
1186
- }
1187
- var ManagedAgentsClient = class {
1188
- constructor(config = {}) {
1189
- this.agents = new AgentsClient(config);
1190
- this.runs = new RunsClient(config);
1191
- this.sessions = new SessionsClient(config);
1192
- this.endUsers = new EndUsersClient(config);
1193
- this.settings = new RuntimeSettingsClient(config);
1194
- }
1195
- };
1196
- // Annotate the CommonJS export names for ESM import in node:
1197
- 0 && (module.exports = {
1198
- ALLOWED_CONFIG_KEYS,
1199
- AgentArchivedError,
1200
- AgentsClient,
1201
- BudgetExceededError,
1202
- ConfigKeyNotAllowedError,
1203
- EVENTS_VERSION,
1204
- EVENTS_VERSION_HEADER,
1205
- EndUsersClient,
1206
- IdempotencyConflictError,
1207
- KNOWN_EVENTS,
1208
- ManagedAgentError,
1209
- ManagedAgentsClient,
1210
- ModelRequiresOwnKeyError,
1211
- ProviderNotConnectedError,
1212
- RunsClient,
1213
- RuntimeSettingsClient,
1214
- SessionAgentMismatchError,
1215
- SessionBusyError,
1216
- SessionEndUserMismatchError,
1217
- SessionsClient,
1218
- SseDecoder,
1219
- eventText,
1220
- isTerminal,
1221
- parseRunEvents,
1222
- parseSseFrames,
1223
- toManagedAgentError,
1224
- toRunEvent
1225
- });
1226
- //# sourceMappingURL=index.cjs.map