@celestoai/sdk 0.1.3 → 0.1.5
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.
- package/README.md +246 -10
- package/dist/agents/index.cjs +1226 -0
- package/dist/agents/index.cjs.map +1 -0
- package/dist/agents/index.d.cts +2 -0
- package/dist/agents/index.d.ts +2 -0
- package/dist/agents/index.js +60 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/{chunk-LPTIN7LO.js → chunk-52TE4RZV.js} +345 -58
- package/dist/chunk-52TE4RZV.js.map +1 -0
- package/dist/chunk-6Y2YZCPU.js +1007 -0
- package/dist/chunk-6Y2YZCPU.js.map +1 -0
- package/dist/{chunk-4KVRJSVJ.js → chunk-P7F52CSQ.js} +2 -2
- package/dist/{chunk-N3HU6ONW.js → chunk-THPVQCTE.js} +41 -6
- package/dist/chunk-THPVQCTE.js.map +1 -0
- package/dist/computers/index.cjs +407 -74
- package/dist/computers/index.cjs.map +1 -1
- package/dist/computers/index.d.cts +96 -15
- package/dist/computers/index.d.ts +96 -15
- package/dist/computers/index.js +10 -4
- package/dist/{config-BTTpuv_b.d.cts → config-dDPvsH-K.d.cts} +18 -1
- package/dist/{config-BTTpuv_b.d.ts → config-dDPvsH-K.d.ts} +18 -1
- package/dist/gatekeeper/index.cjs +14 -4
- package/dist/gatekeeper/index.cjs.map +1 -1
- package/dist/gatekeeper/index.d.cts +1 -1
- package/dist/gatekeeper/index.d.ts +1 -1
- package/dist/gatekeeper/index.js +2 -2
- package/dist/index-Cii1_OFg.d.ts +696 -0
- package/dist/index-CsEA7qMF.d.cts +696 -0
- package/dist/index.cjs +1412 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -21
- package/dist/index.d.ts +3 -21
- package/dist/index.js +61 -5
- package/package.json +11 -3
- package/dist/chunk-LPTIN7LO.js.map +0 -1
- package/dist/chunk-N3HU6ONW.js.map +0 -1
- /package/dist/{chunk-4KVRJSVJ.js.map → chunk-P7F52CSQ.js.map} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,16 +17,51 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
21
31
|
var src_exports = {};
|
|
22
32
|
__export(src_exports, {
|
|
33
|
+
ALLOWED_CONFIG_KEYS: () => ALLOWED_CONFIG_KEYS,
|
|
34
|
+
AgentArchivedError: () => AgentArchivedError,
|
|
35
|
+
AgentsClient: () => AgentsClient,
|
|
36
|
+
BudgetExceededError: () => BudgetExceededError,
|
|
23
37
|
CelestoApiError: () => CelestoApiError,
|
|
24
38
|
CelestoError: () => CelestoError,
|
|
25
39
|
CelestoNetworkError: () => CelestoNetworkError,
|
|
26
40
|
Computer: () => Computer,
|
|
27
|
-
|
|
41
|
+
ConfigKeyNotAllowedError: () => ConfigKeyNotAllowedError,
|
|
42
|
+
EVENTS_VERSION: () => EVENTS_VERSION,
|
|
43
|
+
EndUsersClient: () => EndUsersClient,
|
|
44
|
+
GatekeeperClient: () => GatekeeperClient,
|
|
45
|
+
IdempotencyConflictError: () => IdempotencyConflictError,
|
|
46
|
+
KNOWN_EVENTS: () => KNOWN_EVENTS,
|
|
47
|
+
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
|
+
resolveCelestoApiKey: () => resolveCelestoApiKey,
|
|
63
|
+
resolveClientConfig: () => resolveClientConfig,
|
|
64
|
+
toRunEvent: () => toRunEvent
|
|
28
65
|
});
|
|
29
66
|
module.exports = __toCommonJS(src_exports);
|
|
30
67
|
|
|
@@ -48,12 +85,13 @@ var CelestoError = class extends Error {
|
|
|
48
85
|
}
|
|
49
86
|
};
|
|
50
87
|
var CelestoApiError = class extends CelestoError {
|
|
51
|
-
constructor(message, status, data, requestId) {
|
|
88
|
+
constructor(message, status, data, requestId, headers) {
|
|
52
89
|
super(message);
|
|
53
90
|
this.name = "CelestoApiError";
|
|
54
91
|
this.status = status;
|
|
55
92
|
this.data = data;
|
|
56
93
|
this.requestId = requestId;
|
|
94
|
+
this.headers = headers;
|
|
57
95
|
}
|
|
58
96
|
};
|
|
59
97
|
var CelestoNetworkError = class extends CelestoError {
|
|
@@ -65,9 +103,9 @@ var CelestoNetworkError = class extends CelestoError {
|
|
|
65
103
|
};
|
|
66
104
|
|
|
67
105
|
// src/core/http.ts
|
|
68
|
-
var joinUrl = (baseUrl,
|
|
106
|
+
var joinUrl = (baseUrl, path2) => {
|
|
69
107
|
const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
|
|
70
|
-
const normalizedPath =
|
|
108
|
+
const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
|
|
71
109
|
return `${trimmedBase}${normalizedPath}`;
|
|
72
110
|
};
|
|
73
111
|
var buildQuery = (query) => {
|
|
@@ -115,7 +153,7 @@ var extractErrorMessage = (data, status) => {
|
|
|
115
153
|
}
|
|
116
154
|
return `Request failed with status ${status}`;
|
|
117
155
|
};
|
|
118
|
-
var
|
|
156
|
+
var buildRequestInit = (ctx, options) => {
|
|
119
157
|
const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
|
|
120
158
|
const headers = {
|
|
121
159
|
...ctx.headers ?? {},
|
|
@@ -133,13 +171,16 @@ var request = async (ctx, options) => {
|
|
|
133
171
|
const init = {
|
|
134
172
|
method: options.method,
|
|
135
173
|
headers,
|
|
136
|
-
body: void 0,
|
|
137
174
|
signal: options.signal
|
|
138
175
|
};
|
|
139
176
|
if (options.body !== void 0) {
|
|
140
177
|
headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
141
178
|
init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
|
|
142
179
|
}
|
|
180
|
+
return { url, init };
|
|
181
|
+
};
|
|
182
|
+
var request = async (ctx, options) => {
|
|
183
|
+
const { url, init } = buildRequestInit(ctx, options);
|
|
143
184
|
let timeoutId;
|
|
144
185
|
let controller;
|
|
145
186
|
if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
|
|
@@ -152,7 +193,13 @@ var request = async (ctx, options) => {
|
|
|
152
193
|
const data = await parseResponseBody(response);
|
|
153
194
|
if (!response.ok) {
|
|
154
195
|
const message = extractErrorMessage(data, response.status);
|
|
155
|
-
throw new CelestoApiError(
|
|
196
|
+
throw new CelestoApiError(
|
|
197
|
+
message,
|
|
198
|
+
response.status,
|
|
199
|
+
data,
|
|
200
|
+
response.headers.get("x-request-id") ?? void 0,
|
|
201
|
+
response.headers
|
|
202
|
+
);
|
|
156
203
|
}
|
|
157
204
|
return data;
|
|
158
205
|
} catch (err) {
|
|
@@ -167,6 +214,30 @@ var request = async (ctx, options) => {
|
|
|
167
214
|
}
|
|
168
215
|
}
|
|
169
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);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
170
241
|
|
|
171
242
|
// src/gatekeeper/client.ts
|
|
172
243
|
var toConnectRequest = (payload) => ({
|
|
@@ -219,7 +290,7 @@ var toDriveFile = (payload) => ({
|
|
|
219
290
|
shared: payload.shared ?? null,
|
|
220
291
|
ownedByMe: payload.owned_by_me ?? null
|
|
221
292
|
});
|
|
222
|
-
var gatekeeperPath = (
|
|
293
|
+
var gatekeeperPath = (path2) => `/v1/gatekeeper${path2}`;
|
|
223
294
|
var pickOverrides = (options) => ({
|
|
224
295
|
headers: options?.headers,
|
|
225
296
|
signal: options?.signal
|
|
@@ -336,6 +407,56 @@ var GatekeeperClient = class {
|
|
|
336
407
|
}
|
|
337
408
|
};
|
|
338
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
|
+
|
|
339
460
|
// src/computers/client.ts
|
|
340
461
|
var toConnection2 = (payload) => {
|
|
341
462
|
if (!payload) {
|
|
@@ -368,17 +489,50 @@ var toComputerInfo = (payload) => ({
|
|
|
368
489
|
image: payload.image,
|
|
369
490
|
templateId: payload.template_id,
|
|
370
491
|
templateVersion: payload.template_version ?? null,
|
|
492
|
+
persistentHome: payload.external_volume_enabled ?? false,
|
|
493
|
+
networkPolicy: payload.network_policy ?? { mode: "open" },
|
|
371
494
|
connection: toConnection2(payload.connection),
|
|
372
495
|
publishedPorts: payload.published_ports?.map(toPublishedPortInfo),
|
|
373
496
|
lastError: payload.last_error ?? null,
|
|
374
497
|
createdAt: payload.created_at,
|
|
375
498
|
stoppedAt: payload.stopped_at ?? null
|
|
376
499
|
});
|
|
377
|
-
var toExecResponse = (payload) =>
|
|
500
|
+
var toExecResponse = (payload) => {
|
|
501
|
+
const response = {
|
|
502
|
+
exitCode: payload.exit_code,
|
|
503
|
+
stdout: payload.stdout,
|
|
504
|
+
stderr: payload.stderr
|
|
505
|
+
};
|
|
506
|
+
if (payload.command_id !== void 0) response.commandId = payload.command_id;
|
|
507
|
+
if (payload.duration_ms !== void 0) response.durationMs = payload.duration_ms;
|
|
508
|
+
if (payload.timed_out !== void 0) response.timedOut = payload.timed_out;
|
|
509
|
+
return response;
|
|
510
|
+
};
|
|
511
|
+
var toCommandHistoryEntry = (payload) => ({
|
|
512
|
+
commandId: payload.command_id,
|
|
513
|
+
source: payload.source,
|
|
514
|
+
status: payload.status,
|
|
515
|
+
startedAt: payload.started_at,
|
|
516
|
+
endedAt: payload.ended_at,
|
|
517
|
+
durationMs: payload.duration_ms,
|
|
518
|
+
timeoutSeconds: payload.timeout_seconds,
|
|
378
519
|
exitCode: payload.exit_code,
|
|
379
|
-
|
|
380
|
-
|
|
520
|
+
stdoutBytes: payload.stdout_bytes,
|
|
521
|
+
stderrBytes: payload.stderr_bytes,
|
|
522
|
+
errorType: payload.error_type
|
|
381
523
|
});
|
|
524
|
+
var toTerminalConnectionInfo = (payload) => {
|
|
525
|
+
const separator = payload.gateway_url.includes("?") ? "&" : "?";
|
|
526
|
+
return {
|
|
527
|
+
terminalId: payload.terminal_id,
|
|
528
|
+
gatewayUrl: payload.gateway_url,
|
|
529
|
+
url: `${payload.gateway_url}${separator}token=${encodeURIComponent(payload.token)}`,
|
|
530
|
+
token: payload.token,
|
|
531
|
+
expiresAt: payload.expires_at,
|
|
532
|
+
headers: {},
|
|
533
|
+
firstMessage: ""
|
|
534
|
+
};
|
|
535
|
+
};
|
|
382
536
|
var toSandboxTemplateInfo = (payload) => ({
|
|
383
537
|
id: payload.id,
|
|
384
538
|
displayName: payload.display_name,
|
|
@@ -475,6 +629,16 @@ var buildCreateComputerBody = (params) => {
|
|
|
475
629
|
throw new Error("disk and diskSizeMb must have the same value when both are provided.");
|
|
476
630
|
}
|
|
477
631
|
const body = {};
|
|
632
|
+
if (params.networkPolicy !== void 0) {
|
|
633
|
+
const policy = params.networkPolicy;
|
|
634
|
+
if (!policy || Object.keys(policy).length !== 1 || !("mode" in policy) || !["open", "off"].includes(policy.mode)) {
|
|
635
|
+
throw new Error('networkPolicy must be {mode: "open"} or {mode: "off"}.');
|
|
636
|
+
}
|
|
637
|
+
if (policy.mode === "off" && params.persistentHome) {
|
|
638
|
+
throw new Error("External volumes require internet access; set persistentHome=false.");
|
|
639
|
+
}
|
|
640
|
+
body.network_policy = { mode: policy.mode };
|
|
641
|
+
}
|
|
478
642
|
const vcpus = params.vcpus ?? params.cpus;
|
|
479
643
|
const ramMb = params.ramMb ?? params.memory;
|
|
480
644
|
const diskSizeMb = params.diskSizeMb ?? parsedDiskSizeMb;
|
|
@@ -496,13 +660,109 @@ var buildCreateComputerBody = (params) => {
|
|
|
496
660
|
if (params.templateVersion !== void 0) {
|
|
497
661
|
body.template_version = params.templateVersion;
|
|
498
662
|
}
|
|
663
|
+
if (params.persistentHome !== void 0) {
|
|
664
|
+
body.external_volume_enabled = params.persistentHome;
|
|
665
|
+
}
|
|
499
666
|
return body;
|
|
500
667
|
};
|
|
501
|
-
var computersPath = (
|
|
668
|
+
var computersPath = (path2) => `/v1/computers${path2}`;
|
|
502
669
|
var pickOverrides2 = (options) => ({
|
|
503
670
|
headers: options?.headers,
|
|
504
671
|
signal: options?.signal
|
|
505
672
|
});
|
|
673
|
+
var optionalNumber = (value) => typeof value === "number" ? value : void 0;
|
|
674
|
+
var optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
|
|
675
|
+
var parseExecStreamEvent = (value) => {
|
|
676
|
+
if (!value || typeof value !== "object") {
|
|
677
|
+
throw new Error("Celesto returned an invalid command stream event.");
|
|
678
|
+
}
|
|
679
|
+
const event = value;
|
|
680
|
+
if (event.type === "stdout" || event.type === "stderr") {
|
|
681
|
+
if (typeof event.data !== "string") {
|
|
682
|
+
throw new Error("Celesto returned command output without text data.");
|
|
683
|
+
}
|
|
684
|
+
return { type: event.type, data: event.data };
|
|
685
|
+
}
|
|
686
|
+
if (event.type === "started") {
|
|
687
|
+
if (typeof event.command_id !== "string" || typeof event.started_at_unix_ms !== "number" || typeof event.timeout_seconds !== "number") {
|
|
688
|
+
throw new Error("Celesto returned an invalid command-start event.");
|
|
689
|
+
}
|
|
690
|
+
return {
|
|
691
|
+
type: "started",
|
|
692
|
+
commandId: event.command_id,
|
|
693
|
+
startedAtUnixMs: event.started_at_unix_ms,
|
|
694
|
+
timeoutSeconds: event.timeout_seconds
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
if (event.type === "exit") {
|
|
698
|
+
if (typeof event.exit_code !== "number") {
|
|
699
|
+
throw new Error("Celesto returned an invalid command-exit event.");
|
|
700
|
+
}
|
|
701
|
+
const result = {
|
|
702
|
+
type: "exit",
|
|
703
|
+
exitCode: event.exit_code
|
|
704
|
+
};
|
|
705
|
+
if (typeof event.command_id === "string") result.commandId = event.command_id;
|
|
706
|
+
const startedAtUnixMs = optionalNumber(event.started_at_unix_ms);
|
|
707
|
+
const endedAtUnixMs = optionalNumber(event.ended_at_unix_ms);
|
|
708
|
+
const durationMs = optionalNumber(event.duration_ms);
|
|
709
|
+
const timedOut = optionalBoolean(event.timed_out);
|
|
710
|
+
if (startedAtUnixMs !== void 0) result.startedAtUnixMs = startedAtUnixMs;
|
|
711
|
+
if (endedAtUnixMs !== void 0) result.endedAtUnixMs = endedAtUnixMs;
|
|
712
|
+
if (durationMs !== void 0) result.durationMs = durationMs;
|
|
713
|
+
if (timedOut !== void 0) result.timedOut = timedOut;
|
|
714
|
+
return result;
|
|
715
|
+
}
|
|
716
|
+
throw new Error("Celesto returned an unknown command stream event.");
|
|
717
|
+
};
|
|
718
|
+
var parseSseDataLine = (line) => {
|
|
719
|
+
const text = line.trim();
|
|
720
|
+
if (!text || !text.startsWith("data:")) {
|
|
721
|
+
return void 0;
|
|
722
|
+
}
|
|
723
|
+
const data = text.slice("data:".length).trim();
|
|
724
|
+
if (!data || data === "[DONE]") {
|
|
725
|
+
return void 0;
|
|
726
|
+
}
|
|
727
|
+
try {
|
|
728
|
+
return parseExecStreamEvent(JSON.parse(data));
|
|
729
|
+
} catch (error) {
|
|
730
|
+
if (error instanceof SyntaxError) {
|
|
731
|
+
throw new Error("Celesto returned malformed JSON in the command stream.");
|
|
732
|
+
}
|
|
733
|
+
throw error;
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
var createManagedSignal = (signal, timeoutMs) => {
|
|
737
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
738
|
+
return { signal, cleanup: () => {
|
|
739
|
+
} };
|
|
740
|
+
}
|
|
741
|
+
const controller = new AbortController();
|
|
742
|
+
const abort = () => controller.abort();
|
|
743
|
+
if (signal?.aborted) {
|
|
744
|
+
abort();
|
|
745
|
+
} else {
|
|
746
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
747
|
+
}
|
|
748
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
749
|
+
return {
|
|
750
|
+
signal: controller.signal,
|
|
751
|
+
cleanup: () => {
|
|
752
|
+
clearTimeout(timer);
|
|
753
|
+
signal?.removeEventListener("abort", abort);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
};
|
|
757
|
+
var toNetworkError = (error) => {
|
|
758
|
+
if (error instanceof CelestoNetworkError) return error;
|
|
759
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
760
|
+
return new CelestoNetworkError(cause.message, cause);
|
|
761
|
+
};
|
|
762
|
+
var withFallbackCommandId = (event, commandId) => {
|
|
763
|
+
if (event.type !== "exit" || event.commandId || !commandId) return event;
|
|
764
|
+
return { ...event, commandId };
|
|
765
|
+
};
|
|
506
766
|
var ComputersClient = class {
|
|
507
767
|
constructor(config) {
|
|
508
768
|
this.config = config;
|
|
@@ -554,17 +814,113 @@ var ComputersClient = class {
|
|
|
554
814
|
return toComputerInfo(data);
|
|
555
815
|
}
|
|
556
816
|
async exec(computerId, command, params = {}, options) {
|
|
817
|
+
const ctx = buildRequestContext(this.config);
|
|
818
|
+
const managedSignal = createManagedSignal(
|
|
819
|
+
params.signal ?? options?.signal,
|
|
820
|
+
this.config.timeoutMs
|
|
821
|
+
);
|
|
822
|
+
try {
|
|
823
|
+
const data = await request(ctx, {
|
|
824
|
+
method: "POST",
|
|
825
|
+
path: computersPath(`/${encodeURIComponent(computerId)}/exec`),
|
|
826
|
+
body: {
|
|
827
|
+
command,
|
|
828
|
+
timeout: params.timeout ?? 30
|
|
829
|
+
},
|
|
830
|
+
headers: options?.headers,
|
|
831
|
+
signal: managedSignal.signal
|
|
832
|
+
});
|
|
833
|
+
return toExecResponse(data);
|
|
834
|
+
} finally {
|
|
835
|
+
managedSignal.cleanup();
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
async *execStream(computerId, command, params = {}, options) {
|
|
839
|
+
const ctx = buildRequestContext(this.config);
|
|
840
|
+
const managedSignal = createManagedSignal(
|
|
841
|
+
params.signal ?? options?.signal,
|
|
842
|
+
this.config.timeoutMs
|
|
843
|
+
);
|
|
844
|
+
let reader;
|
|
845
|
+
let completed = false;
|
|
846
|
+
try {
|
|
847
|
+
const response = await requestStream(ctx, {
|
|
848
|
+
method: "POST",
|
|
849
|
+
path: computersPath(`/${encodeURIComponent(computerId)}/exec/stream`),
|
|
850
|
+
body: {
|
|
851
|
+
command,
|
|
852
|
+
timeout: params.timeout ?? 30
|
|
853
|
+
},
|
|
854
|
+
headers: options?.headers,
|
|
855
|
+
signal: managedSignal.signal
|
|
856
|
+
});
|
|
857
|
+
if (!response.body) {
|
|
858
|
+
throw new Error("Celesto did not return a command output stream.");
|
|
859
|
+
}
|
|
860
|
+
const responseCommandId = response.headers.get("x-celesto-command-id") ?? void 0;
|
|
861
|
+
reader = response.body.getReader();
|
|
862
|
+
const decoder = new TextDecoder();
|
|
863
|
+
let buffer = "";
|
|
864
|
+
while (true) {
|
|
865
|
+
let chunk;
|
|
866
|
+
try {
|
|
867
|
+
chunk = await reader.read();
|
|
868
|
+
} catch (error) {
|
|
869
|
+
throw toNetworkError(error);
|
|
870
|
+
}
|
|
871
|
+
if (chunk.done) {
|
|
872
|
+
completed = true;
|
|
873
|
+
buffer += decoder.decode();
|
|
874
|
+
break;
|
|
875
|
+
}
|
|
876
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
877
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
878
|
+
while (newlineIndex !== -1) {
|
|
879
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
880
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
881
|
+
const parsed = parseSseDataLine(line);
|
|
882
|
+
if (parsed) {
|
|
883
|
+
const event = withFallbackCommandId(parsed, responseCommandId);
|
|
884
|
+
yield event;
|
|
885
|
+
if (event.type === "exit") return;
|
|
886
|
+
}
|
|
887
|
+
newlineIndex = buffer.indexOf("\n");
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (buffer) {
|
|
891
|
+
const parsed = parseSseDataLine(buffer);
|
|
892
|
+
if (parsed) {
|
|
893
|
+
const event = withFallbackCommandId(parsed, responseCommandId);
|
|
894
|
+
yield event;
|
|
895
|
+
if (event.type === "exit") return;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
throw new Error("Command stream ended before Celesto returned an exit status.");
|
|
899
|
+
} finally {
|
|
900
|
+
if (reader) {
|
|
901
|
+
if (!completed) {
|
|
902
|
+
try {
|
|
903
|
+
await reader.cancel();
|
|
904
|
+
} catch {
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
reader.releaseLock();
|
|
908
|
+
}
|
|
909
|
+
managedSignal.cleanup();
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
async listCommandHistory(computerId, params = {}, options) {
|
|
557
913
|
const ctx = buildRequestContext(this.config);
|
|
558
914
|
const data = await request(ctx, {
|
|
559
|
-
method: "
|
|
560
|
-
path: computersPath(`/${encodeURIComponent(computerId)}/
|
|
561
|
-
|
|
562
|
-
command,
|
|
563
|
-
timeout: params.timeout ?? 30
|
|
564
|
-
},
|
|
915
|
+
method: "GET",
|
|
916
|
+
path: computersPath(`/${encodeURIComponent(computerId)}/commands`),
|
|
917
|
+
query: { limit: params.limit },
|
|
565
918
|
...pickOverrides2(options)
|
|
566
919
|
});
|
|
567
|
-
return
|
|
920
|
+
return {
|
|
921
|
+
commands: data.commands.map(toCommandHistoryEntry),
|
|
922
|
+
count: data.count
|
|
923
|
+
};
|
|
568
924
|
}
|
|
569
925
|
async stop(computerId, options) {
|
|
570
926
|
const ctx = buildRequestContext(this.config);
|
|
@@ -621,43 +977,19 @@ var ComputersClient = class {
|
|
|
621
977
|
});
|
|
622
978
|
return toPublishedPortInfo(data);
|
|
623
979
|
}
|
|
624
|
-
/**
|
|
625
|
-
|
|
626
|
-
*
|
|
627
|
-
* Accepts either a computer ID (e.g. `cmp_xxx`) or a human-readable name.
|
|
628
|
-
* The name is resolved to the canonical ID via a GET call — the backend's
|
|
629
|
-
* WebSocket endpoint does not resolve names on its own.
|
|
630
|
-
*
|
|
631
|
-
* Returns the URL, headers, and first message needed to open the connection
|
|
632
|
-
* with any WebSocket library of your choice.
|
|
633
|
-
*
|
|
634
|
-
* @example
|
|
635
|
-
* ```ts
|
|
636
|
-
* const conn = await client.getTerminalConnection("my-computer");
|
|
637
|
-
* const ws = new WebSocket(conn.url, { headers: conn.headers });
|
|
638
|
-
* ws.on("open", () => ws.send(conn.firstMessage));
|
|
639
|
-
* ws.on("message", (data) => process.stdout.write(data));
|
|
640
|
-
* ```
|
|
641
|
-
*/
|
|
642
|
-
async getTerminalConnection(computerIdOrName) {
|
|
643
|
-
const info = await this.get(computerIdOrName);
|
|
980
|
+
/** Create a short-lived direct connection to Celesto's terminal gateway. */
|
|
981
|
+
async createTerminalSession(computerIdOrName, options) {
|
|
644
982
|
const ctx = buildRequestContext(this.config);
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
}
|
|
656
|
-
return {
|
|
657
|
-
url,
|
|
658
|
-
headers,
|
|
659
|
-
firstMessage: JSON.stringify({ token: ctx.token })
|
|
660
|
-
};
|
|
983
|
+
const data = await request(ctx, {
|
|
984
|
+
method: "POST",
|
|
985
|
+
path: computersPath(`/${encodeURIComponent(computerIdOrName)}/terminals`),
|
|
986
|
+
...pickOverrides2(options)
|
|
987
|
+
});
|
|
988
|
+
return toTerminalConnectionInfo(data);
|
|
989
|
+
}
|
|
990
|
+
/** @deprecated Use createTerminalSession(). */
|
|
991
|
+
async getTerminalConnection(computerIdOrName, options) {
|
|
992
|
+
return this.createTerminalSession(computerIdOrName, options);
|
|
661
993
|
}
|
|
662
994
|
};
|
|
663
995
|
|
|
@@ -671,26 +1003,26 @@ var Computer = class _Computer {
|
|
|
671
1003
|
this.info = info;
|
|
672
1004
|
}
|
|
673
1005
|
/** Create a new computer and return an object with methods on it. */
|
|
674
|
-
static async create(params = {}, config
|
|
675
|
-
const client = new ComputersClient(config);
|
|
1006
|
+
static async create(params = {}, config) {
|
|
1007
|
+
const client = new ComputersClient(await resolveClientConfig(config));
|
|
676
1008
|
const info = await client.create(params);
|
|
677
1009
|
return new _Computer(client, info);
|
|
678
1010
|
}
|
|
679
1011
|
/** Load an existing computer by name or ID. */
|
|
680
|
-
static async get(computerIdOrName, config
|
|
681
|
-
const client = new ComputersClient(config);
|
|
1012
|
+
static async get(computerIdOrName, config) {
|
|
1013
|
+
const client = new ComputersClient(await resolveClientConfig(config));
|
|
682
1014
|
const info = await client.get(computerIdOrName);
|
|
683
1015
|
return new _Computer(client, info);
|
|
684
1016
|
}
|
|
685
1017
|
/** List computers in the current account. */
|
|
686
|
-
static async list(params = {}, config
|
|
687
|
-
const client = new ComputersClient(config);
|
|
1018
|
+
static async list(params = {}, config) {
|
|
1019
|
+
const client = new ComputersClient(await resolveClientConfig(config));
|
|
688
1020
|
const response = await client.list(params);
|
|
689
1021
|
return response.computers.map((info) => new _Computer(client, info));
|
|
690
1022
|
}
|
|
691
1023
|
/** List available computer templates. */
|
|
692
|
-
static async listTemplates(config
|
|
693
|
-
const client = new ComputersClient(config);
|
|
1024
|
+
static async listTemplates(config) {
|
|
1025
|
+
const client = new ComputersClient(await resolveClientConfig(config));
|
|
694
1026
|
return client.listTemplates();
|
|
695
1027
|
}
|
|
696
1028
|
/** Wrap an existing API response in the convenience object. */
|
|
@@ -760,6 +1092,26 @@ var Computer = class _Computer {
|
|
|
760
1092
|
async exec(command, params = {}) {
|
|
761
1093
|
return this.run(command, params);
|
|
762
1094
|
}
|
|
1095
|
+
/** Run a shell command and stream output and exit events as they arrive. */
|
|
1096
|
+
runStream(command, params = {}) {
|
|
1097
|
+
return this.client.execStream(this.id, command, params);
|
|
1098
|
+
}
|
|
1099
|
+
/** Alias for runStream(). */
|
|
1100
|
+
execStream(command, params = {}) {
|
|
1101
|
+
return this.runStream(command, params);
|
|
1102
|
+
}
|
|
1103
|
+
/** List recent commands executed on this computer. */
|
|
1104
|
+
async listCommandHistory(params = {}) {
|
|
1105
|
+
return this.client.listCommandHistory(this.id, params);
|
|
1106
|
+
}
|
|
1107
|
+
/** Create a short-lived direct connection to Celesto's terminal gateway. */
|
|
1108
|
+
async createTerminalSession() {
|
|
1109
|
+
return this.client.createTerminalSession(this.id);
|
|
1110
|
+
}
|
|
1111
|
+
/** @deprecated Use createTerminalSession(). */
|
|
1112
|
+
async getTerminalConnection() {
|
|
1113
|
+
return this.createTerminalSession();
|
|
1114
|
+
}
|
|
763
1115
|
/** Stop this computer and update the local data. */
|
|
764
1116
|
async stop() {
|
|
765
1117
|
this.info = await this.client.stop(this.id);
|
|
@@ -801,12 +1153,1008 @@ var Computer = class _Computer {
|
|
|
801
1153
|
return unpublished;
|
|
802
1154
|
}
|
|
803
1155
|
};
|
|
1156
|
+
|
|
1157
|
+
// src/agents/errors.ts
|
|
1158
|
+
var ManagedAgentError = class extends CelestoApiError {
|
|
1159
|
+
constructor(message, status, data, options = {}) {
|
|
1160
|
+
super(message, status, data, options.requestId, options.headers);
|
|
1161
|
+
/** True when retrying the identical request can succeed. */
|
|
1162
|
+
this.retryable = false;
|
|
1163
|
+
this.name = "ManagedAgentError";
|
|
1164
|
+
this.code = options.code;
|
|
1165
|
+
this.retryAfter = options.retryAfter;
|
|
1166
|
+
}
|
|
1167
|
+
};
|
|
1168
|
+
var BudgetExceededError = class extends ManagedAgentError {
|
|
1169
|
+
constructor(...args) {
|
|
1170
|
+
super(...args);
|
|
1171
|
+
this.name = "BudgetExceededError";
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
var SessionBusyError = class extends ManagedAgentError {
|
|
1175
|
+
constructor(...args) {
|
|
1176
|
+
super(...args);
|
|
1177
|
+
this.retryable = true;
|
|
1178
|
+
this.name = "SessionBusyError";
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
var IdempotencyConflictError = class extends ManagedAgentError {
|
|
1182
|
+
constructor(...args) {
|
|
1183
|
+
super(...args);
|
|
1184
|
+
this.name = "IdempotencyConflictError";
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
var AgentArchivedError = class extends ManagedAgentError {
|
|
1188
|
+
constructor(...args) {
|
|
1189
|
+
super(...args);
|
|
1190
|
+
this.name = "AgentArchivedError";
|
|
1191
|
+
}
|
|
1192
|
+
};
|
|
1193
|
+
var ProviderNotConnectedError = class extends ManagedAgentError {
|
|
1194
|
+
constructor(...args) {
|
|
1195
|
+
super(...args);
|
|
1196
|
+
this.name = "ProviderNotConnectedError";
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
var SessionAgentMismatchError = class extends ManagedAgentError {
|
|
1200
|
+
constructor(...args) {
|
|
1201
|
+
super(...args);
|
|
1202
|
+
this.name = "SessionAgentMismatchError";
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
var SessionEndUserMismatchError = class extends ManagedAgentError {
|
|
1206
|
+
constructor(...args) {
|
|
1207
|
+
super(...args);
|
|
1208
|
+
this.name = "SessionEndUserMismatchError";
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
var ModelRequiresOwnKeyError = class extends ManagedAgentError {
|
|
1212
|
+
constructor(...args) {
|
|
1213
|
+
super(...args);
|
|
1214
|
+
this.name = "ModelRequiresOwnKeyError";
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
var ConfigKeyNotAllowedError = class extends ManagedAgentError {
|
|
1218
|
+
constructor(...args) {
|
|
1219
|
+
super(...args);
|
|
1220
|
+
this.name = "ConfigKeyNotAllowedError";
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
var ERROR_CLASSES = {
|
|
1224
|
+
budget_exceeded: BudgetExceededError,
|
|
1225
|
+
session_busy: SessionBusyError,
|
|
1226
|
+
idempotency_conflict: IdempotencyConflictError,
|
|
1227
|
+
agent_archived: AgentArchivedError,
|
|
1228
|
+
provider_not_connected: ProviderNotConnectedError,
|
|
1229
|
+
session_agent_mismatch: SessionAgentMismatchError,
|
|
1230
|
+
session_end_user_mismatch: SessionEndUserMismatchError,
|
|
1231
|
+
model_requires_own_key: ModelRequiresOwnKeyError,
|
|
1232
|
+
config_key_not_allowed: ConfigKeyNotAllowedError
|
|
1233
|
+
};
|
|
1234
|
+
var STATUS_FALLBACK = {
|
|
1235
|
+
402: BudgetExceededError
|
|
1236
|
+
};
|
|
1237
|
+
var readErrorCode = (data) => {
|
|
1238
|
+
if (!data || typeof data !== "object") return void 0;
|
|
1239
|
+
const record = data;
|
|
1240
|
+
const detail = record.detail;
|
|
1241
|
+
const raw = detail && typeof detail === "object" ? detail.code : record.code;
|
|
1242
|
+
if (typeof raw !== "string") return void 0;
|
|
1243
|
+
return raw in ERROR_CLASSES ? raw : void 0;
|
|
1244
|
+
};
|
|
1245
|
+
var readMessage = (data, fallback) => {
|
|
1246
|
+
if (data && typeof data === "object") {
|
|
1247
|
+
const detail = data.detail;
|
|
1248
|
+
if (detail && typeof detail === "object") {
|
|
1249
|
+
const message = detail.message;
|
|
1250
|
+
if (typeof message === "string") return message;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
return fallback;
|
|
1254
|
+
};
|
|
1255
|
+
var readRetryAfter = (headers) => {
|
|
1256
|
+
const raw = headers?.get("retry-after");
|
|
1257
|
+
if (!raw) return void 0;
|
|
1258
|
+
const seconds = Number(raw);
|
|
1259
|
+
return Number.isFinite(seconds) ? seconds : void 0;
|
|
1260
|
+
};
|
|
1261
|
+
var toManagedAgentError = (error) => {
|
|
1262
|
+
if (!(error instanceof CelestoApiError) || error instanceof ManagedAgentError) {
|
|
1263
|
+
return error;
|
|
1264
|
+
}
|
|
1265
|
+
const code = readErrorCode(error.data);
|
|
1266
|
+
const ErrorClass = (code && ERROR_CLASSES[code]) ?? STATUS_FALLBACK[error.status];
|
|
1267
|
+
if (!ErrorClass) return error;
|
|
1268
|
+
return new ErrorClass(readMessage(error.data, error.message), error.status, error.data, {
|
|
1269
|
+
code: code ?? (error.status === 402 ? "budget_exceeded" : void 0),
|
|
1270
|
+
retryAfter: readRetryAfter(error.headers),
|
|
1271
|
+
requestId: error.requestId,
|
|
1272
|
+
headers: error.headers
|
|
1273
|
+
});
|
|
1274
|
+
};
|
|
1275
|
+
|
|
1276
|
+
// src/agents/events.ts
|
|
1277
|
+
var EVENTS_VERSION = "1";
|
|
1278
|
+
var KNOWN_EVENTS = [
|
|
1279
|
+
"run.started",
|
|
1280
|
+
"message.delta",
|
|
1281
|
+
"message.completed",
|
|
1282
|
+
"tool.call",
|
|
1283
|
+
"tool.result",
|
|
1284
|
+
"usage",
|
|
1285
|
+
"run.completed",
|
|
1286
|
+
"run.failed"
|
|
1287
|
+
];
|
|
1288
|
+
var KNOWN_EVENT_SET = new Set(KNOWN_EVENTS);
|
|
1289
|
+
var asRecord = (value) => value && typeof value === "object" ? value : {};
|
|
1290
|
+
var str = (value) => typeof value === "string" ? value : null;
|
|
1291
|
+
var num = (value) => typeof value === "number" ? value : null;
|
|
1292
|
+
var int = (value) => typeof value === "number" ? value : 0;
|
|
1293
|
+
var money = (value) => typeof value === "string" ? value : "0.000000";
|
|
1294
|
+
var toUsage = (value) => {
|
|
1295
|
+
const raw = asRecord(value);
|
|
1296
|
+
return {
|
|
1297
|
+
inputTokens: int(raw.input_tokens),
|
|
1298
|
+
outputTokens: int(raw.output_tokens),
|
|
1299
|
+
totalTokens: int(raw.total_tokens),
|
|
1300
|
+
costUsd: money(raw.cost_usd)
|
|
1301
|
+
};
|
|
1302
|
+
};
|
|
1303
|
+
var toToolResultData = (raw) => {
|
|
1304
|
+
const data = {
|
|
1305
|
+
callId: str(raw.call_id),
|
|
1306
|
+
name: str(raw.name),
|
|
1307
|
+
turn: num(raw.turn)
|
|
1308
|
+
};
|
|
1309
|
+
if ("error" in raw) {
|
|
1310
|
+
data.error = raw.error;
|
|
1311
|
+
} else {
|
|
1312
|
+
data.result = raw.result;
|
|
1313
|
+
}
|
|
1314
|
+
return data;
|
|
1315
|
+
};
|
|
1316
|
+
var toRunEvent = (frame) => {
|
|
1317
|
+
const name = frame.event;
|
|
1318
|
+
if (!name || !KNOWN_EVENT_SET.has(name)) return void 0;
|
|
1319
|
+
let parsed;
|
|
1320
|
+
try {
|
|
1321
|
+
parsed = frame.data ? JSON.parse(frame.data) : {};
|
|
1322
|
+
} catch {
|
|
1323
|
+
return void 0;
|
|
1324
|
+
}
|
|
1325
|
+
const raw = asRecord(parsed);
|
|
1326
|
+
const seq = frame.id !== void 0 && frame.id !== "" ? Number(frame.id) : NaN;
|
|
1327
|
+
const position = Number.isFinite(seq) ? seq : null;
|
|
1328
|
+
switch (name) {
|
|
1329
|
+
case "run.started":
|
|
1330
|
+
return {
|
|
1331
|
+
name: "run.started",
|
|
1332
|
+
seq: position,
|
|
1333
|
+
data: {
|
|
1334
|
+
runId: str(raw.run_id) ?? "",
|
|
1335
|
+
agentId: str(raw.agent_id) ?? "",
|
|
1336
|
+
agentVersionId: str(raw.agent_version_id) ?? "",
|
|
1337
|
+
sessionId: str(raw.session_id) ?? "",
|
|
1338
|
+
endUserId: str(raw.end_user_id) ?? "",
|
|
1339
|
+
model: str(raw.model) ?? "",
|
|
1340
|
+
createdAt: str(raw.created_at) ?? ""
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
case "message.delta":
|
|
1344
|
+
return {
|
|
1345
|
+
name: "message.delta",
|
|
1346
|
+
seq: position,
|
|
1347
|
+
data: { text: str(raw.text), turn: num(raw.turn) }
|
|
1348
|
+
};
|
|
1349
|
+
case "message.completed":
|
|
1350
|
+
return {
|
|
1351
|
+
name: "message.completed",
|
|
1352
|
+
seq: position,
|
|
1353
|
+
data: { text: str(raw.text), turn: num(raw.turn) }
|
|
1354
|
+
};
|
|
1355
|
+
case "tool.call":
|
|
1356
|
+
return {
|
|
1357
|
+
name: "tool.call",
|
|
1358
|
+
seq: position,
|
|
1359
|
+
data: {
|
|
1360
|
+
callId: str(raw.call_id),
|
|
1361
|
+
name: str(raw.name),
|
|
1362
|
+
args: raw.args,
|
|
1363
|
+
turn: num(raw.turn)
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
case "tool.result":
|
|
1367
|
+
return { name: "tool.result", seq: position, data: toToolResultData(raw) };
|
|
1368
|
+
case "usage":
|
|
1369
|
+
return {
|
|
1370
|
+
name: "usage",
|
|
1371
|
+
seq: position,
|
|
1372
|
+
data: {
|
|
1373
|
+
turn: num(raw.turn),
|
|
1374
|
+
model: str(raw.model),
|
|
1375
|
+
inputTokens: int(raw.input_tokens),
|
|
1376
|
+
outputTokens: int(raw.output_tokens),
|
|
1377
|
+
totalTokens: int(raw.total_tokens),
|
|
1378
|
+
costUsd: money(raw.cost_usd)
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
case "run.completed":
|
|
1382
|
+
return {
|
|
1383
|
+
name: "run.completed",
|
|
1384
|
+
seq: position,
|
|
1385
|
+
data: {
|
|
1386
|
+
runId: str(raw.run_id) ?? "",
|
|
1387
|
+
status: str(raw.status) ?? "completed",
|
|
1388
|
+
output: str(raw.output),
|
|
1389
|
+
turnCount: num(raw.turn_count),
|
|
1390
|
+
usage: toUsage(raw.usage)
|
|
1391
|
+
}
|
|
1392
|
+
};
|
|
1393
|
+
case "run.failed":
|
|
1394
|
+
return {
|
|
1395
|
+
name: "run.failed",
|
|
1396
|
+
seq: position,
|
|
1397
|
+
data: {
|
|
1398
|
+
runId: str(raw.run_id) ?? "",
|
|
1399
|
+
status: str(raw.status) ?? "failed",
|
|
1400
|
+
errorCode: str(raw.error_code),
|
|
1401
|
+
error: str(raw.error),
|
|
1402
|
+
turnCount: num(raw.turn_count),
|
|
1403
|
+
usage: toUsage(raw.usage)
|
|
1404
|
+
}
|
|
1405
|
+
};
|
|
1406
|
+
default:
|
|
1407
|
+
return void 0;
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
var isTerminal = (event) => event.name === "run.completed" || event.name === "run.failed";
|
|
1411
|
+
var eventText = (event) => {
|
|
1412
|
+
switch (event.name) {
|
|
1413
|
+
case "message.delta":
|
|
1414
|
+
case "message.completed":
|
|
1415
|
+
return event.data.text ?? "";
|
|
1416
|
+
case "run.completed":
|
|
1417
|
+
return event.data.output ?? "";
|
|
1418
|
+
default:
|
|
1419
|
+
return "";
|
|
1420
|
+
}
|
|
1421
|
+
};
|
|
1422
|
+
var SseDecoder = class {
|
|
1423
|
+
constructor() {
|
|
1424
|
+
this.buffer = "";
|
|
1425
|
+
}
|
|
1426
|
+
push(chunk) {
|
|
1427
|
+
this.buffer += chunk;
|
|
1428
|
+
const frames = [];
|
|
1429
|
+
let boundary = this.findBoundary();
|
|
1430
|
+
while (boundary) {
|
|
1431
|
+
const block = this.buffer.slice(0, boundary.index);
|
|
1432
|
+
this.buffer = this.buffer.slice(boundary.index + boundary.length);
|
|
1433
|
+
const frame = parseFrame(block);
|
|
1434
|
+
if (frame) frames.push(frame);
|
|
1435
|
+
boundary = this.findBoundary();
|
|
1436
|
+
}
|
|
1437
|
+
return frames;
|
|
1438
|
+
}
|
|
1439
|
+
/** Anything left in the buffer when the stream ends. */
|
|
1440
|
+
flush() {
|
|
1441
|
+
const block = this.buffer;
|
|
1442
|
+
this.buffer = "";
|
|
1443
|
+
const frame = parseFrame(block);
|
|
1444
|
+
return frame ? [frame] : [];
|
|
1445
|
+
}
|
|
1446
|
+
findBoundary() {
|
|
1447
|
+
const lf = this.buffer.indexOf("\n\n");
|
|
1448
|
+
const crlf = this.buffer.indexOf("\r\n\r\n");
|
|
1449
|
+
if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
|
|
1450
|
+
if (lf !== -1) return { index: lf, length: 2 };
|
|
1451
|
+
return void 0;
|
|
1452
|
+
}
|
|
1453
|
+
};
|
|
1454
|
+
var parseFrame = (block) => {
|
|
1455
|
+
let event;
|
|
1456
|
+
let id;
|
|
1457
|
+
const dataLines = [];
|
|
1458
|
+
let sawField = false;
|
|
1459
|
+
for (const rawLine of block.split("\n")) {
|
|
1460
|
+
const line = rawLine.replace(/\r$/, "");
|
|
1461
|
+
if (line === "" || line.startsWith(":")) continue;
|
|
1462
|
+
const separator = line.indexOf(":");
|
|
1463
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
1464
|
+
let value = separator === -1 ? "" : line.slice(separator + 1);
|
|
1465
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
1466
|
+
if (field === "event") {
|
|
1467
|
+
event = value;
|
|
1468
|
+
sawField = true;
|
|
1469
|
+
} else if (field === "data") {
|
|
1470
|
+
dataLines.push(value);
|
|
1471
|
+
sawField = true;
|
|
1472
|
+
} else if (field === "id") {
|
|
1473
|
+
id = value;
|
|
1474
|
+
sawField = true;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
if (!sawField) return void 0;
|
|
1478
|
+
const frame = { data: dataLines.join("\n") };
|
|
1479
|
+
if (event !== void 0) frame.event = event;
|
|
1480
|
+
if (id !== void 0) frame.id = id;
|
|
1481
|
+
return frame;
|
|
1482
|
+
};
|
|
1483
|
+
var parseSseFrames = (body) => {
|
|
1484
|
+
const decoder = new SseDecoder();
|
|
1485
|
+
return [...decoder.push(body), ...decoder.flush()];
|
|
1486
|
+
};
|
|
1487
|
+
var parseRunEvents = (body) => {
|
|
1488
|
+
const events = [];
|
|
1489
|
+
for (const frame of parseSseFrames(body)) {
|
|
1490
|
+
const event = toRunEvent(frame);
|
|
1491
|
+
if (event) events.push(event);
|
|
1492
|
+
}
|
|
1493
|
+
return events;
|
|
1494
|
+
};
|
|
1495
|
+
|
|
1496
|
+
// src/agents/client.ts
|
|
1497
|
+
var runtimePath = (path2) => `/v1${path2}`;
|
|
1498
|
+
var pickOverrides3 = (options) => ({
|
|
1499
|
+
headers: options?.headers,
|
|
1500
|
+
signal: options?.signal
|
|
1501
|
+
});
|
|
1502
|
+
var DEFAULT_RETRY_BACKOFF_MS = 1e3;
|
|
1503
|
+
var CONFIG_KEYS = {
|
|
1504
|
+
temperature: "temperature",
|
|
1505
|
+
topP: "top_p",
|
|
1506
|
+
maxTokens: "max_tokens",
|
|
1507
|
+
maxOutputTokens: "max_output_tokens",
|
|
1508
|
+
frequencyPenalty: "frequency_penalty",
|
|
1509
|
+
presencePenalty: "presence_penalty",
|
|
1510
|
+
seed: "seed",
|
|
1511
|
+
stop: "stop",
|
|
1512
|
+
reasoningEffort: "reasoning_effort",
|
|
1513
|
+
verbosity: "verbosity",
|
|
1514
|
+
maxTurns: "max_turns"
|
|
1515
|
+
};
|
|
1516
|
+
var ALLOWED_CONFIG_KEYS = Object.keys(CONFIG_KEYS);
|
|
1517
|
+
var WIRE_TO_CONFIG_KEY = new Map(
|
|
1518
|
+
Object.entries(CONFIG_KEYS).map(([key, wire]) => [
|
|
1519
|
+
wire,
|
|
1520
|
+
key
|
|
1521
|
+
])
|
|
1522
|
+
);
|
|
1523
|
+
var toConfigWire = (config) => {
|
|
1524
|
+
if (!config) return void 0;
|
|
1525
|
+
const wire = {};
|
|
1526
|
+
const unknown = [];
|
|
1527
|
+
for (const [key, value] of Object.entries(config)) {
|
|
1528
|
+
if (value === void 0) continue;
|
|
1529
|
+
const wireKey = CONFIG_KEYS[key];
|
|
1530
|
+
if (!wireKey) {
|
|
1531
|
+
unknown.push(key);
|
|
1532
|
+
continue;
|
|
1533
|
+
}
|
|
1534
|
+
wire[wireKey] = value;
|
|
1535
|
+
}
|
|
1536
|
+
if (unknown.length > 0) {
|
|
1537
|
+
throw new ConfigKeyNotAllowedError(
|
|
1538
|
+
`Agent config does not accept ${unknown.join(", ")}. It accepts only: ${ALLOWED_CONFIG_KEYS.join(", ")}.`,
|
|
1539
|
+
422,
|
|
1540
|
+
void 0,
|
|
1541
|
+
{ code: "config_key_not_allowed" }
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
return wire;
|
|
1545
|
+
};
|
|
1546
|
+
var toConfig = (wire) => {
|
|
1547
|
+
if (!wire || typeof wire !== "object") return null;
|
|
1548
|
+
const config = {};
|
|
1549
|
+
for (const [wireKey, value] of Object.entries(wire)) {
|
|
1550
|
+
const key = WIRE_TO_CONFIG_KEY.get(wireKey);
|
|
1551
|
+
config[key ?? wireKey] = value;
|
|
1552
|
+
}
|
|
1553
|
+
return config;
|
|
1554
|
+
};
|
|
1555
|
+
var toAgent = (wire) => ({
|
|
1556
|
+
id: wire.id,
|
|
1557
|
+
object: wire.object ?? "agent",
|
|
1558
|
+
name: wire.name,
|
|
1559
|
+
description: wire.description ?? null,
|
|
1560
|
+
model: wire.model,
|
|
1561
|
+
instructions: wire.instructions ?? null,
|
|
1562
|
+
config: toConfig(wire.config),
|
|
1563
|
+
version: wire.version,
|
|
1564
|
+
currentVersionId: wire.current_version_id,
|
|
1565
|
+
projectId: wire.project_id,
|
|
1566
|
+
organizationId: wire.organization_id,
|
|
1567
|
+
status: wire.status,
|
|
1568
|
+
createdAt: wire.created_at,
|
|
1569
|
+
updatedAt: wire.updated_at
|
|
1570
|
+
});
|
|
1571
|
+
var toAgentVersion = (wire) => ({
|
|
1572
|
+
id: wire.id,
|
|
1573
|
+
object: wire.object ?? "agent_version",
|
|
1574
|
+
agentId: wire.agent_id,
|
|
1575
|
+
version: wire.version,
|
|
1576
|
+
name: wire.name,
|
|
1577
|
+
description: wire.description ?? null,
|
|
1578
|
+
model: wire.model,
|
|
1579
|
+
instructions: wire.instructions ?? null,
|
|
1580
|
+
config: toConfig(wire.config),
|
|
1581
|
+
createdAt: wire.created_at
|
|
1582
|
+
});
|
|
1583
|
+
var toUsage2 = (wire) => ({
|
|
1584
|
+
inputTokens: wire.input_tokens,
|
|
1585
|
+
outputTokens: wire.output_tokens,
|
|
1586
|
+
totalTokens: wire.total_tokens,
|
|
1587
|
+
// Money stays a string. Never parseFloat this.
|
|
1588
|
+
costUsd: wire.cost_usd
|
|
1589
|
+
});
|
|
1590
|
+
var toRun = (wire) => ({
|
|
1591
|
+
runId: wire.run_id,
|
|
1592
|
+
object: wire.object ?? "run",
|
|
1593
|
+
status: wire.status,
|
|
1594
|
+
errorCode: wire.error_code ?? null,
|
|
1595
|
+
error: wire.error ?? null,
|
|
1596
|
+
output: wire.output ?? null,
|
|
1597
|
+
usage: toUsage2(wire.usage),
|
|
1598
|
+
agentId: wire.agent_id,
|
|
1599
|
+
agentVersionId: wire.agent_version_id,
|
|
1600
|
+
sessionId: wire.session_id,
|
|
1601
|
+
endUserId: wire.end_user_id,
|
|
1602
|
+
turnCount: wire.turn_count ?? null,
|
|
1603
|
+
createdAt: wire.created_at,
|
|
1604
|
+
startedAt: wire.started_at ?? null,
|
|
1605
|
+
endedAt: wire.ended_at ?? null
|
|
1606
|
+
});
|
|
1607
|
+
var toSession = (wire) => ({
|
|
1608
|
+
id: wire.id,
|
|
1609
|
+
object: wire.object ?? "session",
|
|
1610
|
+
agentId: wire.agent_id ?? null,
|
|
1611
|
+
endUserId: wire.end_user_id,
|
|
1612
|
+
status: wire.status,
|
|
1613
|
+
messageCount: wire.message_count,
|
|
1614
|
+
lastMessageAt: wire.last_message_at ?? null,
|
|
1615
|
+
createdAt: wire.created_at
|
|
1616
|
+
});
|
|
1617
|
+
var toSessionMessage = (wire) => ({
|
|
1618
|
+
seq: wire.seq,
|
|
1619
|
+
role: wire.role ?? null,
|
|
1620
|
+
item: wire.item,
|
|
1621
|
+
createdAt: wire.created_at
|
|
1622
|
+
});
|
|
1623
|
+
var toBudget = (wire) => ({
|
|
1624
|
+
capUsd: wire.cap_usd ?? null,
|
|
1625
|
+
source: wire.source,
|
|
1626
|
+
windowStart: wire.window_start,
|
|
1627
|
+
windowResetsAt: wire.window_resets_at,
|
|
1628
|
+
spentUsd: wire.spent_usd,
|
|
1629
|
+
remainingUsd: wire.remaining_usd ?? null
|
|
1630
|
+
});
|
|
1631
|
+
var toEndUser = (wire) => ({
|
|
1632
|
+
endUserId: wire.end_user_id,
|
|
1633
|
+
object: wire.object ?? "end_user",
|
|
1634
|
+
firstActivityAt: wire.first_activity_at,
|
|
1635
|
+
budget: toBudget(wire.budget),
|
|
1636
|
+
metadata: wire.metadata ?? null,
|
|
1637
|
+
createdAt: wire.created_at
|
|
1638
|
+
});
|
|
1639
|
+
var toRuntimeSettings = (wire) => ({
|
|
1640
|
+
organizationId: wire.organization_id,
|
|
1641
|
+
defaultEndUserBudgetUsd: wire.default_end_user_budget_usd ?? null
|
|
1642
|
+
});
|
|
1643
|
+
var toPage = (wire, map) => ({
|
|
1644
|
+
data: (wire.data ?? []).map(map),
|
|
1645
|
+
hasMore: wire.has_more ?? false
|
|
1646
|
+
});
|
|
1647
|
+
var MONEY_PATTERN = /^\d{1,8}(\.\d{1,6})?$/;
|
|
1648
|
+
var toMoneyString = (value) => {
|
|
1649
|
+
if (typeof value === "number") {
|
|
1650
|
+
throw new TypeError(
|
|
1651
|
+
`Budget amounts cannot be a number (${value}): a JavaScript number cannot hold these amounts exactly. Pass a decimal string instead \u2014 "5.00", not 5.0.`
|
|
1652
|
+
);
|
|
1653
|
+
}
|
|
1654
|
+
const text = value.trim();
|
|
1655
|
+
if (!MONEY_PATTERN.test(text)) {
|
|
1656
|
+
throw new TypeError(
|
|
1657
|
+
`"${value}" is not a valid amount. Use a plain decimal amount with at most 8 digits before the point and 6 after, like "5.00" \u2014 no sign, no exponent, no currency symbol.`
|
|
1658
|
+
);
|
|
1659
|
+
}
|
|
1660
|
+
return text;
|
|
1661
|
+
};
|
|
1662
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1663
|
+
var newIdempotencyKey = () => {
|
|
1664
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
1665
|
+
return uuid ?? `idem_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
1666
|
+
};
|
|
1667
|
+
var BaseClient = class {
|
|
1668
|
+
constructor(config) {
|
|
1669
|
+
this.config = config;
|
|
1670
|
+
}
|
|
1671
|
+
/** Every call goes through here, so refusals arrive already typed. */
|
|
1672
|
+
async call(options) {
|
|
1673
|
+
try {
|
|
1674
|
+
return await request(buildRequestContext(this.config), options);
|
|
1675
|
+
} catch (error) {
|
|
1676
|
+
throw toManagedAgentError(error);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
var AgentsClient = class extends BaseClient {
|
|
1681
|
+
/** Create an agent, at version 1. */
|
|
1682
|
+
async create(params, options) {
|
|
1683
|
+
const wire = await this.call({
|
|
1684
|
+
method: "POST",
|
|
1685
|
+
path: runtimePath("/agents"),
|
|
1686
|
+
body: {
|
|
1687
|
+
name: params.name,
|
|
1688
|
+
model: params.model,
|
|
1689
|
+
instructions: params.instructions,
|
|
1690
|
+
description: params.description,
|
|
1691
|
+
config: toConfigWire(params.config),
|
|
1692
|
+
project_id: params.projectId
|
|
1693
|
+
},
|
|
1694
|
+
...pickOverrides3(options)
|
|
1695
|
+
});
|
|
1696
|
+
return toAgent(wire);
|
|
1697
|
+
}
|
|
1698
|
+
/** List one page of agents. Check `hasMore`; there is no total count. */
|
|
1699
|
+
async list(params = {}, options) {
|
|
1700
|
+
const wire = await this.call({
|
|
1701
|
+
method: "GET",
|
|
1702
|
+
path: runtimePath("/agents"),
|
|
1703
|
+
query: {
|
|
1704
|
+
project_id: params.projectId,
|
|
1705
|
+
include_archived: params.includeArchived,
|
|
1706
|
+
limit: params.limit,
|
|
1707
|
+
offset: params.offset
|
|
1708
|
+
},
|
|
1709
|
+
...pickOverrides3(options)
|
|
1710
|
+
});
|
|
1711
|
+
return toPage(wire, toAgent);
|
|
1712
|
+
}
|
|
1713
|
+
/** Yield every agent, fetching pages as you go. */
|
|
1714
|
+
async *listAll(params = {}, options) {
|
|
1715
|
+
const pageSize = params.limit ?? 50;
|
|
1716
|
+
let offset = 0;
|
|
1717
|
+
for (; ; ) {
|
|
1718
|
+
const page = await this.list({ ...params, limit: pageSize, offset }, options);
|
|
1719
|
+
yield* page.data;
|
|
1720
|
+
if (page.data.length === 0 || !page.hasMore) return;
|
|
1721
|
+
offset += page.data.length;
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
/** Get an agent, at its current version. */
|
|
1725
|
+
async get(agentId, options) {
|
|
1726
|
+
const wire = await this.call({
|
|
1727
|
+
method: "GET",
|
|
1728
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
|
|
1729
|
+
...pickOverrides3(options)
|
|
1730
|
+
});
|
|
1731
|
+
return toAgent(wire);
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Replace an agent's definition, which cuts a new version.
|
|
1735
|
+
*
|
|
1736
|
+
* This is a full replacement, not a patch: whatever you leave out is
|
|
1737
|
+
* cleared. Read the agent first if you only mean to change one field.
|
|
1738
|
+
*/
|
|
1739
|
+
async update(agentId, params, options) {
|
|
1740
|
+
const wire = await this.call({
|
|
1741
|
+
method: "PUT",
|
|
1742
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
|
|
1743
|
+
body: {
|
|
1744
|
+
name: params.name,
|
|
1745
|
+
model: params.model,
|
|
1746
|
+
instructions: params.instructions,
|
|
1747
|
+
description: params.description,
|
|
1748
|
+
config: toConfigWire(params.config)
|
|
1749
|
+
},
|
|
1750
|
+
...pickOverrides3(options)
|
|
1751
|
+
});
|
|
1752
|
+
return toAgent(wire);
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Archive an agent. Archived agents refuse new runs.
|
|
1756
|
+
*
|
|
1757
|
+
* Past runs, versions, and transcripts stay readable.
|
|
1758
|
+
*/
|
|
1759
|
+
async archive(agentId, options) {
|
|
1760
|
+
const wire = await this.call({
|
|
1761
|
+
method: "DELETE",
|
|
1762
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}`),
|
|
1763
|
+
...pickOverrides3(options)
|
|
1764
|
+
});
|
|
1765
|
+
return { id: wire.id, status: wire.status };
|
|
1766
|
+
}
|
|
1767
|
+
/** List one page of an agent's versions. */
|
|
1768
|
+
async listVersions(agentId, params = {}, options) {
|
|
1769
|
+
const wire = await this.call({
|
|
1770
|
+
method: "GET",
|
|
1771
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions`),
|
|
1772
|
+
query: { limit: params.limit, offset: params.offset },
|
|
1773
|
+
...pickOverrides3(options)
|
|
1774
|
+
});
|
|
1775
|
+
return toPage(wire, toAgentVersion);
|
|
1776
|
+
}
|
|
1777
|
+
/** Yield every version of an agent, fetching pages as you go. */
|
|
1778
|
+
async *listAllVersions(agentId, params = {}, options) {
|
|
1779
|
+
const pageSize = params.limit ?? 50;
|
|
1780
|
+
let offset = 0;
|
|
1781
|
+
for (; ; ) {
|
|
1782
|
+
const page = await this.listVersions(agentId, { limit: pageSize, offset }, options);
|
|
1783
|
+
yield* page.data;
|
|
1784
|
+
if (page.data.length === 0 || !page.hasMore) return;
|
|
1785
|
+
offset += page.data.length;
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
/** Get one version of an agent by its number. */
|
|
1789
|
+
async getVersion(agentId, versionNumber, options) {
|
|
1790
|
+
const wire = await this.call({
|
|
1791
|
+
method: "GET",
|
|
1792
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}`),
|
|
1793
|
+
...pickOverrides3(options)
|
|
1794
|
+
});
|
|
1795
|
+
return toAgentVersion(wire);
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Roll back to an earlier version.
|
|
1799
|
+
*
|
|
1800
|
+
* This moves the agent's pointer; it does not cut a new version and nothing
|
|
1801
|
+
* is lost.
|
|
1802
|
+
*/
|
|
1803
|
+
async activateVersion(agentId, versionNumber, options) {
|
|
1804
|
+
const wire = await this.call({
|
|
1805
|
+
method: "POST",
|
|
1806
|
+
path: runtimePath(
|
|
1807
|
+
`/agents/${encodeURIComponent(agentId)}/versions/${versionNumber}/activate`
|
|
1808
|
+
),
|
|
1809
|
+
...pickOverrides3(options)
|
|
1810
|
+
});
|
|
1811
|
+
return toAgent(wire);
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
var RunsClient = class extends BaseClient {
|
|
1815
|
+
runBody(params, stream) {
|
|
1816
|
+
return {
|
|
1817
|
+
input: params.input,
|
|
1818
|
+
end_user_id: params.endUserId,
|
|
1819
|
+
session_id: params.sessionId,
|
|
1820
|
+
max_turns: params.maxTurns,
|
|
1821
|
+
stream
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
/** Retrying without a key can charge twice, so make one when retrying. */
|
|
1825
|
+
idempotencyKey(params) {
|
|
1826
|
+
if (params.idempotencyKey) return params.idempotencyKey;
|
|
1827
|
+
return (params.maxRetries ?? 0) > 0 ? newIdempotencyKey() : void 0;
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Run an agent and wait for the answer.
|
|
1831
|
+
*
|
|
1832
|
+
* @throws {@link BudgetExceededError} when the end user has spent their budget.
|
|
1833
|
+
* @throws {@link SessionBusyError} when another run holds the session.
|
|
1834
|
+
*/
|
|
1835
|
+
async create(agentId, params, options) {
|
|
1836
|
+
const key = this.idempotencyKey(params);
|
|
1837
|
+
const maxRetries = params.maxRetries ?? 0;
|
|
1838
|
+
const headers = {
|
|
1839
|
+
...options?.headers ?? {},
|
|
1840
|
+
...key ? { "Idempotency-Key": key } : {}
|
|
1841
|
+
};
|
|
1842
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1843
|
+
try {
|
|
1844
|
+
const wire = await this.call({
|
|
1845
|
+
method: "POST",
|
|
1846
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
|
|
1847
|
+
body: this.runBody(params, false),
|
|
1848
|
+
headers,
|
|
1849
|
+
signal: options?.signal
|
|
1850
|
+
});
|
|
1851
|
+
return toRun(wire);
|
|
1852
|
+
} catch (error) {
|
|
1853
|
+
if (!(error instanceof SessionBusyError) || attempt >= maxRetries) throw error;
|
|
1854
|
+
await sleep(
|
|
1855
|
+
error.retryAfter !== void 0 ? error.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
|
|
1856
|
+
);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Run an agent and watch it work.
|
|
1862
|
+
*
|
|
1863
|
+
* Yields events as the run happens: text as it is generated, each tool call
|
|
1864
|
+
* and its result, what each generation cost, and finally `run.completed` or
|
|
1865
|
+
* `run.failed`. Event names this SDK does not know are ignored, so a newer
|
|
1866
|
+
* server cannot break an older client.
|
|
1867
|
+
*
|
|
1868
|
+
* A failed run arrives as a `run.failed` event, not a thrown error —
|
|
1869
|
+
* including a run stopped mid-stream because the end user ran out of
|
|
1870
|
+
* budget. Errors are thrown for runs that never started.
|
|
1871
|
+
*
|
|
1872
|
+
* A replay of an idempotency key omits `message.delta`: partial text is
|
|
1873
|
+
* never stored, so there is nothing to replay.
|
|
1874
|
+
*
|
|
1875
|
+
* @example
|
|
1876
|
+
* ```ts
|
|
1877
|
+
* for await (const event of celesto.runs.stream(agent.id, {
|
|
1878
|
+
* input: "Where is my order?",
|
|
1879
|
+
* endUserId: "usr_8837",
|
|
1880
|
+
* })) {
|
|
1881
|
+
* if (event.name === "message.delta") process.stdout.write(event.data.text ?? "");
|
|
1882
|
+
* }
|
|
1883
|
+
* ```
|
|
1884
|
+
*/
|
|
1885
|
+
async *stream(agentId, params, options) {
|
|
1886
|
+
const key = this.idempotencyKey(params);
|
|
1887
|
+
const maxRetries = params.maxRetries ?? 0;
|
|
1888
|
+
const headers = {
|
|
1889
|
+
Accept: "text/event-stream",
|
|
1890
|
+
...options?.headers ?? {},
|
|
1891
|
+
...key ? { "Idempotency-Key": key } : {}
|
|
1892
|
+
};
|
|
1893
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1894
|
+
let response;
|
|
1895
|
+
try {
|
|
1896
|
+
response = await requestStream(buildRequestContext(this.config), {
|
|
1897
|
+
method: "POST",
|
|
1898
|
+
path: runtimePath(`/agents/${encodeURIComponent(agentId)}/runs`),
|
|
1899
|
+
body: this.runBody(params, true),
|
|
1900
|
+
headers,
|
|
1901
|
+
signal: options?.signal
|
|
1902
|
+
});
|
|
1903
|
+
} catch (error) {
|
|
1904
|
+
const typed = toManagedAgentError(error);
|
|
1905
|
+
if (!(typed instanceof SessionBusyError) || attempt >= maxRetries) throw typed;
|
|
1906
|
+
await sleep(
|
|
1907
|
+
typed.retryAfter !== void 0 ? typed.retryAfter * 1e3 : DEFAULT_RETRY_BACKOFF_MS
|
|
1908
|
+
);
|
|
1909
|
+
continue;
|
|
1910
|
+
}
|
|
1911
|
+
yield* readEventStream(response);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
/** Get a run by id, settled or not. */
|
|
1916
|
+
async get(runId, options) {
|
|
1917
|
+
const wire = await this.call({
|
|
1918
|
+
method: "GET",
|
|
1919
|
+
path: runtimePath(`/runs/${encodeURIComponent(runId)}`),
|
|
1920
|
+
...pickOverrides3(options)
|
|
1921
|
+
});
|
|
1922
|
+
return toRun(wire);
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Read one page of a run's stored events.
|
|
1926
|
+
*
|
|
1927
|
+
* The same event contract as {@link stream}, read back after the fact,
|
|
1928
|
+
* minus `message.delta` — partial text is never stored.
|
|
1929
|
+
*/
|
|
1930
|
+
async listEvents(runId, params = {}, options) {
|
|
1931
|
+
const wire = await this.call({
|
|
1932
|
+
method: "GET",
|
|
1933
|
+
path: runtimePath(`/runs/${encodeURIComponent(runId)}/events`),
|
|
1934
|
+
query: { after_seq: params.afterSeq, limit: params.limit },
|
|
1935
|
+
...pickOverrides3(options)
|
|
1936
|
+
});
|
|
1937
|
+
return { data: wire.data ?? [], eventsVersion: wire.events_version };
|
|
1938
|
+
}
|
|
1939
|
+
/** Yield every stored event of a run, in order, fetching pages as you go. */
|
|
1940
|
+
async *listAllEvents(runId, params = {}, options) {
|
|
1941
|
+
const pageSize = params.limit ?? 100;
|
|
1942
|
+
let afterSeq = params.afterSeq ?? 0;
|
|
1943
|
+
for (; ; ) {
|
|
1944
|
+
const page = await this.listEvents(runId, { afterSeq, limit: pageSize }, options);
|
|
1945
|
+
yield* page.data;
|
|
1946
|
+
if (page.data.length < pageSize) return;
|
|
1947
|
+
const last = page.data[page.data.length - 1];
|
|
1948
|
+
if (!last) return;
|
|
1949
|
+
afterSeq = last.seq;
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
};
|
|
1953
|
+
var SessionsClient = class extends BaseClient {
|
|
1954
|
+
/** List one page of an end user's sessions. */
|
|
1955
|
+
async list(params, options) {
|
|
1956
|
+
const wire = await this.call({
|
|
1957
|
+
method: "GET",
|
|
1958
|
+
path: runtimePath("/sessions"),
|
|
1959
|
+
query: {
|
|
1960
|
+
end_user_id: params.endUserId,
|
|
1961
|
+
limit: params.limit,
|
|
1962
|
+
offset: params.offset
|
|
1963
|
+
},
|
|
1964
|
+
...pickOverrides3(options)
|
|
1965
|
+
});
|
|
1966
|
+
return toPage(wire, toSession);
|
|
1967
|
+
}
|
|
1968
|
+
/** Yield every session for an end user, fetching pages as you go. */
|
|
1969
|
+
async *listAll(params, options) {
|
|
1970
|
+
const pageSize = params.limit ?? 50;
|
|
1971
|
+
let offset = 0;
|
|
1972
|
+
for (; ; ) {
|
|
1973
|
+
const page = await this.list({ ...params, limit: pageSize, offset }, options);
|
|
1974
|
+
yield* page.data;
|
|
1975
|
+
if (page.data.length === 0 || !page.hasMore) return;
|
|
1976
|
+
offset += page.data.length;
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* Get a session and a page of its transcript.
|
|
1981
|
+
*
|
|
1982
|
+
* The transcript pages backwards: `beforeSeq` asks for what came before a
|
|
1983
|
+
* message you already have.
|
|
1984
|
+
*/
|
|
1985
|
+
async get(sessionId, params = {}, options) {
|
|
1986
|
+
const wire = await this.call({
|
|
1987
|
+
method: "GET",
|
|
1988
|
+
path: runtimePath(`/sessions/${encodeURIComponent(sessionId)}`),
|
|
1989
|
+
query: { limit: params.limit, before_seq: params.beforeSeq },
|
|
1990
|
+
...pickOverrides3(options)
|
|
1991
|
+
});
|
|
1992
|
+
return {
|
|
1993
|
+
session: toSession(wire.session),
|
|
1994
|
+
messages: (wire.messages ?? []).map(toSessionMessage)
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
/** Yield a session's messages newest first, fetching pages as you go. */
|
|
1998
|
+
async *listAllMessages(sessionId, params = {}, options) {
|
|
1999
|
+
const pageSize = params.limit ?? 50;
|
|
2000
|
+
let beforeSeq = params.beforeSeq;
|
|
2001
|
+
for (; ; ) {
|
|
2002
|
+
const transcript = await this.get(sessionId, { limit: pageSize, beforeSeq }, options);
|
|
2003
|
+
const messages = transcript.messages;
|
|
2004
|
+
if (messages.length === 0) return;
|
|
2005
|
+
yield* [...messages].sort((a, b) => b.seq - a.seq);
|
|
2006
|
+
if (messages.length < pageSize) return;
|
|
2007
|
+
beforeSeq = messages.reduce((lowest, m) => Math.min(lowest, m.seq), Infinity);
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2011
|
+
var EndUsersClient = class extends BaseClient {
|
|
2012
|
+
/** Get an end user's budget and activity. */
|
|
2013
|
+
async get(endUserId, options) {
|
|
2014
|
+
const wire = await this.call({
|
|
2015
|
+
method: "GET",
|
|
2016
|
+
path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
|
|
2017
|
+
...pickOverrides3(options)
|
|
2018
|
+
});
|
|
2019
|
+
return toEndUser(wire);
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Set an end user's budget override or metadata, creating them if needed.
|
|
2023
|
+
*
|
|
2024
|
+
* Fields you do not pass are left alone. Passing `null` clears the field:
|
|
2025
|
+
* `budgetCapUsd: null` drops back to your organization's default budget.
|
|
2026
|
+
*/
|
|
2027
|
+
async update(endUserId, params, options) {
|
|
2028
|
+
const body = {};
|
|
2029
|
+
if (params.budgetCapUsd !== void 0) {
|
|
2030
|
+
body.budget_cap_usd = params.budgetCapUsd === null ? null : toMoneyString(params.budgetCapUsd);
|
|
2031
|
+
}
|
|
2032
|
+
if (params.metadata !== void 0) {
|
|
2033
|
+
body.metadata = params.metadata;
|
|
2034
|
+
}
|
|
2035
|
+
const wire = await this.call({
|
|
2036
|
+
method: "PUT",
|
|
2037
|
+
path: runtimePath(`/end_users/${encodeURIComponent(endUserId)}`),
|
|
2038
|
+
body,
|
|
2039
|
+
...pickOverrides3(options)
|
|
2040
|
+
});
|
|
2041
|
+
return toEndUser(wire);
|
|
2042
|
+
}
|
|
2043
|
+
/** Drop an end user's override, back to the organization default. */
|
|
2044
|
+
async clearBudget(endUserId, options) {
|
|
2045
|
+
return this.update(endUserId, { budgetCapUsd: null }, options);
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
var RuntimeSettingsClient = class extends BaseClient {
|
|
2049
|
+
/** Read the default budget every end user starts with. */
|
|
2050
|
+
async get(options) {
|
|
2051
|
+
const wire = await this.call({
|
|
2052
|
+
method: "GET",
|
|
2053
|
+
path: runtimePath("/runtime/settings"),
|
|
2054
|
+
...pickOverrides3(options)
|
|
2055
|
+
});
|
|
2056
|
+
return toRuntimeSettings(wire);
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Set the default budget every end user starts with.
|
|
2060
|
+
*
|
|
2061
|
+
* Pass `null` to remove the default, which leaves end users uncapped unless
|
|
2062
|
+
* they have their own override.
|
|
2063
|
+
*/
|
|
2064
|
+
async update(params, options) {
|
|
2065
|
+
const body = {};
|
|
2066
|
+
if (params.defaultEndUserBudgetUsd !== void 0) {
|
|
2067
|
+
body.default_end_user_budget_usd = params.defaultEndUserBudgetUsd === null ? null : toMoneyString(params.defaultEndUserBudgetUsd);
|
|
2068
|
+
}
|
|
2069
|
+
const wire = await this.call({
|
|
2070
|
+
method: "PUT",
|
|
2071
|
+
path: runtimePath("/runtime/settings"),
|
|
2072
|
+
body,
|
|
2073
|
+
...pickOverrides3(options)
|
|
2074
|
+
});
|
|
2075
|
+
return toRuntimeSettings(wire);
|
|
2076
|
+
}
|
|
2077
|
+
};
|
|
2078
|
+
async function* readEventStream(response) {
|
|
2079
|
+
if (!response.body) {
|
|
2080
|
+
throw new Error("Celesto did not return a run event stream.");
|
|
2081
|
+
}
|
|
2082
|
+
const reader = response.body.getReader();
|
|
2083
|
+
const textDecoder = new TextDecoder();
|
|
2084
|
+
const sse = new SseDecoder();
|
|
2085
|
+
let completed = false;
|
|
2086
|
+
try {
|
|
2087
|
+
for (; ; ) {
|
|
2088
|
+
const chunk = await reader.read();
|
|
2089
|
+
if (chunk.done) {
|
|
2090
|
+
completed = true;
|
|
2091
|
+
for (const frame of sse.push(textDecoder.decode())) {
|
|
2092
|
+
const event = toRunEvent(frame);
|
|
2093
|
+
if (event) yield event;
|
|
2094
|
+
}
|
|
2095
|
+
for (const frame of sse.flush()) {
|
|
2096
|
+
const event = toRunEvent(frame);
|
|
2097
|
+
if (event) yield event;
|
|
2098
|
+
}
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
for (const frame of sse.push(textDecoder.decode(chunk.value, { stream: true }))) {
|
|
2102
|
+
const event = toRunEvent(frame);
|
|
2103
|
+
if (event) yield event;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
} finally {
|
|
2107
|
+
if (!completed) {
|
|
2108
|
+
try {
|
|
2109
|
+
await reader.cancel();
|
|
2110
|
+
} catch {
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
reader.releaseLock();
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
var ManagedAgentsClient = class {
|
|
2117
|
+
constructor(config = {}) {
|
|
2118
|
+
this.agents = new AgentsClient(config);
|
|
2119
|
+
this.runs = new RunsClient(config);
|
|
2120
|
+
this.sessions = new SessionsClient(config);
|
|
2121
|
+
this.endUsers = new EndUsersClient(config);
|
|
2122
|
+
this.settings = new RuntimeSettingsClient(config);
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
804
2125
|
// Annotate the CommonJS export names for ESM import in node:
|
|
805
2126
|
0 && (module.exports = {
|
|
2127
|
+
ALLOWED_CONFIG_KEYS,
|
|
2128
|
+
AgentArchivedError,
|
|
2129
|
+
AgentsClient,
|
|
2130
|
+
BudgetExceededError,
|
|
806
2131
|
CelestoApiError,
|
|
807
2132
|
CelestoError,
|
|
808
2133
|
CelestoNetworkError,
|
|
809
2134
|
Computer,
|
|
810
|
-
|
|
2135
|
+
ConfigKeyNotAllowedError,
|
|
2136
|
+
EVENTS_VERSION,
|
|
2137
|
+
EndUsersClient,
|
|
2138
|
+
GatekeeperClient,
|
|
2139
|
+
IdempotencyConflictError,
|
|
2140
|
+
KNOWN_EVENTS,
|
|
2141
|
+
MISSING_CREDENTIALS_MESSAGE,
|
|
2142
|
+
ManagedAgentError,
|
|
2143
|
+
ManagedAgentsClient,
|
|
2144
|
+
ModelRequiresOwnKeyError,
|
|
2145
|
+
ProviderNotConnectedError,
|
|
2146
|
+
RunsClient,
|
|
2147
|
+
RuntimeSettingsClient,
|
|
2148
|
+
SessionAgentMismatchError,
|
|
2149
|
+
SessionBusyError,
|
|
2150
|
+
SessionEndUserMismatchError,
|
|
2151
|
+
SessionsClient,
|
|
2152
|
+
eventText,
|
|
2153
|
+
isTerminal,
|
|
2154
|
+
parseRunEvents,
|
|
2155
|
+
parseSseFrames,
|
|
2156
|
+
resolveCelestoApiKey,
|
|
2157
|
+
resolveClientConfig,
|
|
2158
|
+
toRunEvent
|
|
811
2159
|
});
|
|
812
2160
|
//# sourceMappingURL=index.cjs.map
|