@celestoai/sdk 0.1.4 → 0.1.6

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