@getsupervisor/agents-studio-sdk 1.41.0 → 1.41.1-beta.162

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/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ __export(index_exports, {
22
22
  HttpError: () => HttpError,
23
23
  NetworkError: () => NetworkError,
24
24
  TimeoutError: () => TimeoutError,
25
+ WorkspaceNotSelectedError: () => WorkspaceNotSelectedError,
25
26
  bindAgentBlueprints: () => bindAgentBlueprints,
26
27
  bindAgentPhones: () => bindAgentPhones,
27
28
  bindAgentSchedule: () => bindAgentSchedule,
@@ -42,15 +43,22 @@ __export(index_exports, {
42
43
  createAgentVersionsApi: () => createAgentVersionsApi,
43
44
  createAgentsApi: () => createAgentsApi,
44
45
  createApiKeysApi: () => createApiKeysApi,
46
+ createBillingApi: () => createBillingApi,
47
+ createCallsApi: () => createCallsApi,
45
48
  createCampaignsApi: () => createCampaignsApi,
46
49
  createCatalogTemplatesApi: () => createCatalogTemplatesApi,
47
50
  createCatalogsApi: () => createCatalogsApi,
48
51
  createClient: () => createClient,
52
+ createDocumentsApi: () => createDocumentsApi,
49
53
  createHttp: () => createHttp,
54
+ createSipTrunksApi: () => createSipTrunksApi,
50
55
  createToolsApi: () => createToolsApi,
56
+ createUsageApi: () => createUsageApi,
51
57
  createVoicesApi: () => createVoicesApi,
52
58
  createWebhooksApi: () => createWebhooksApi,
53
- createWorkspacesApi: () => createWorkspacesApi
59
+ createWorkspacesApi: () => createWorkspacesApi,
60
+ isApiErrorBody: () => isApiErrorBody,
61
+ isApiHttpError: () => isApiHttpError
54
62
  });
55
63
  module.exports = __toCommonJS(index_exports);
56
64
 
@@ -65,6 +73,14 @@ var HttpError = class extends Error {
65
73
  this.name = "HttpError";
66
74
  }
67
75
  };
76
+ function isApiErrorBody(body) {
77
+ if (!body || typeof body !== "object") return false;
78
+ const candidate = body;
79
+ return typeof candidate.code === "string" && typeof candidate.message === "string";
80
+ }
81
+ function isApiHttpError(err) {
82
+ return err instanceof HttpError && isApiErrorBody(err.body);
83
+ }
68
84
  var TimeoutError = class extends Error {
69
85
  constructor(ms, url) {
70
86
  super(`Timeout after ${ms}ms`);
@@ -81,6 +97,12 @@ var NetworkError = class extends Error {
81
97
  this.name = "NetworkError";
82
98
  }
83
99
  };
100
+ var WorkspaceNotSelectedError = class extends Error {
101
+ constructor() {
102
+ super("Workspace is not selected");
103
+ this.name = "WorkspaceNotSelectedError";
104
+ }
105
+ };
84
106
 
85
107
  // src/http.ts
86
108
  function toQueryString(query) {
@@ -221,7 +243,8 @@ function createHttp(cfg) {
221
243
  }
222
244
  return res;
223
245
  } catch (e) {
224
- if (e.name === "AbortError") throw new TimeoutError(timeout, targetUrl);
246
+ if (e?.name === "AbortError")
247
+ throw new TimeoutError(timeout, targetUrl);
225
248
  if (e instanceof HttpError) throw e;
226
249
  throw new NetworkError(e, targetUrl);
227
250
  }
@@ -242,6 +265,11 @@ function createHttp(cfg) {
242
265
  }
243
266
 
244
267
  // src/utils/query.ts
268
+ function buildSearchParams(entries) {
269
+ const searchParams = new URLSearchParams();
270
+ entries.forEach(([key, value]) => appendParam(searchParams, key, value));
271
+ return searchParams;
272
+ }
245
273
  function serializeListOptions(options = {}, extra = {}) {
246
274
  const params = new URLSearchParams();
247
275
  appendParam(params, "page", options.page);
@@ -927,6 +955,117 @@ function createAgentVersionsApi(cfg) {
927
955
  };
928
956
  }
929
957
 
958
+ // src/utils/sse-stream.ts
959
+ function extractField(line, prefix) {
960
+ if (!line.startsWith(prefix)) {
961
+ return null;
962
+ }
963
+ return line.slice(prefix.length);
964
+ }
965
+ function parseSseMessage(raw) {
966
+ let type = "";
967
+ let data = "";
968
+ for (const line of raw.split("\n")) {
969
+ type = extractField(line, "event: ") ?? type;
970
+ data = extractField(line, "data: ") ?? data;
971
+ }
972
+ if (!type || !data) {
973
+ return null;
974
+ }
975
+ return { type, data };
976
+ }
977
+ function dispatchSseEvent(event, handlers) {
978
+ const handler = handlers[event.type];
979
+ if (!handler) {
980
+ return;
981
+ }
982
+ try {
983
+ const parsed = JSON.parse(event.data);
984
+ handler(parsed);
985
+ return parsed;
986
+ } catch {
987
+ return;
988
+ }
989
+ }
990
+ function processRawPart(raw, handlers, resolveEvent) {
991
+ const trimmed = raw.trim();
992
+ if (!trimmed) {
993
+ return;
994
+ }
995
+ const event = parseSseMessage(trimmed);
996
+ if (!event) {
997
+ return;
998
+ }
999
+ const result = dispatchSseEvent(event, handlers);
1000
+ if (event.type !== resolveEvent) {
1001
+ return;
1002
+ }
1003
+ return result;
1004
+ }
1005
+ function flushRemainingBuffer(buffer) {
1006
+ if (!buffer.trim()) {
1007
+ return "";
1008
+ }
1009
+ return buffer + "\n\n";
1010
+ }
1011
+ function consumeSseStream(response, handlers, resolveEvent, options = {}) {
1012
+ if (!response.body) {
1013
+ throw new Error("No response body for SSE stream");
1014
+ }
1015
+ return new Promise((resolve, reject) => {
1016
+ let resolved;
1017
+ let settled = false;
1018
+ let buffer = "";
1019
+ const reader = response.body.getReader();
1020
+ const decoder = new TextDecoder();
1021
+ const processBuffer = () => {
1022
+ const parts = buffer.split("\n\n");
1023
+ buffer = parts.pop() ?? "";
1024
+ for (const part of parts) {
1025
+ const result = processRawPart(part, handlers, resolveEvent);
1026
+ if (result) {
1027
+ resolved = result;
1028
+ }
1029
+ }
1030
+ };
1031
+ const tryResolveImmediately = () => {
1032
+ if (!options.resolveImmediately || resolved === void 0 || settled) {
1033
+ return false;
1034
+ }
1035
+ settled = true;
1036
+ resolve(resolved);
1037
+ reader.cancel().catch(() => void 0);
1038
+ return true;
1039
+ };
1040
+ const finalize = () => {
1041
+ if (settled) return;
1042
+ buffer = flushRemainingBuffer(buffer);
1043
+ processBuffer();
1044
+ if (resolved) {
1045
+ resolve(resolved);
1046
+ return;
1047
+ }
1048
+ reject(new Error(`SSE stream ended without '${resolveEvent}' event`));
1049
+ };
1050
+ const read = () => {
1051
+ if (settled) return;
1052
+ reader.read().then(({ done, value }) => {
1053
+ if (done) {
1054
+ finalize();
1055
+ return;
1056
+ }
1057
+ buffer += decoder.decode(value, { stream: true });
1058
+ processBuffer();
1059
+ if (tryResolveImmediately()) {
1060
+ return;
1061
+ }
1062
+ read();
1063
+ }).catch(reject);
1064
+ };
1065
+ read();
1066
+ });
1067
+ }
1068
+
930
1069
  // src/entities/agent.ts
931
1070
  var bindAgentStageTriggers = (api, agentId, blueprintId, stageId) => ({
932
1071
  list(opts) {
@@ -1113,7 +1252,8 @@ var createAgentEntity = (dto, options) => {
1113
1252
  stageTriggersApi,
1114
1253
  reload,
1115
1254
  updateAgent,
1116
- deleteAgent
1255
+ deleteAgent,
1256
+ cloneAgent
1117
1257
  } = options;
1118
1258
  const schedulesHelper = bindAgentSchedules(
1119
1259
  scheduleApi,
@@ -1132,6 +1272,9 @@ var createAgentEntity = (dto, options) => {
1132
1272
  async save(patch) {
1133
1273
  return updateAgent(dto.agentId, patch);
1134
1274
  },
1275
+ async clone(payload) {
1276
+ return cloneAgent(dto.agentId, payload);
1277
+ },
1135
1278
  async delete() {
1136
1279
  await deleteAgent(dto.agentId);
1137
1280
  },
@@ -1143,128 +1286,229 @@ var createAgentEntity = (dto, options) => {
1143
1286
  };
1144
1287
 
1145
1288
  // src/api/agents.ts
1289
+ function normalizeCloneSelection(selection) {
1290
+ if (!selection) {
1291
+ return [];
1292
+ }
1293
+ if (Array.isArray(selection)) {
1294
+ return selection;
1295
+ }
1296
+ return Object.entries(selection).filter(([, enabled]) => enabled).map(([component]) => component);
1297
+ }
1298
+ function buildCloneRequest(payload) {
1299
+ const { clone, ...rest } = payload;
1300
+ return { ...rest, clone: normalizeCloneSelection(clone) };
1301
+ }
1302
+ function buildSseHandlers(callbacks) {
1303
+ const onAgent = (data) => callbacks.onAgentCreated?.(data);
1304
+ return {
1305
+ "agent-created": onAgent,
1306
+ agent: onAgent,
1307
+ "runtime-progress": (data) => callbacks.onProgress?.(data),
1308
+ "runtime-complete": (data) => callbacks.onComplete?.(data),
1309
+ "runtime-error": (data) => callbacks.onError?.(data)
1310
+ };
1311
+ }
1312
+ function resolveAgentId(agent) {
1313
+ if (typeof agent === "string") {
1314
+ return agent;
1315
+ }
1316
+ return agent.agentId;
1317
+ }
1146
1318
  function createAgentsApi(cfg, relatedApis) {
1147
- const { base, doFetch } = createHttp(cfg);
1319
+ const { base, doFetch, buildHeaders, resolveWorkspaceId, resolveApiKey } = createHttp(cfg);
1148
1320
  const jsonHeaders = { "content-type": "application/json" };
1149
- const fetchAgentsPage = async (options = {}) => {
1150
- const sanitizedOptions = {
1151
- page: options.page,
1152
- limit: options.limit,
1153
- filter: options.filter
1154
- };
1155
- const query = serializeListOptions(sanitizedOptions);
1156
- const res = await doFetch(`${base}/agents`, {
1157
- method: "GET",
1158
- query
1159
- });
1160
- return res.json();
1161
- };
1162
- const listAgents = async (options = {}) => {
1163
- const normalizedOptions = { ...options ?? {} };
1164
- const response = await fetchAgentsPage(normalizedOptions);
1165
- return attachPaginator(response, fetchAgentsPage, normalizedOptions);
1166
- };
1167
- const getAgentDetail = async (agentId) => {
1168
- const res = await doFetch(`${base}/agents/${agentId}`, {
1169
- method: "GET"
1170
- });
1171
- return res.json();
1321
+ const requireWorkspace = () => {
1322
+ const workspaceId = resolveWorkspaceId();
1323
+ if (typeof workspaceId === "string" && workspaceId.trim().length > 0) {
1324
+ return;
1325
+ }
1326
+ const apiKey = resolveApiKey();
1327
+ if (typeof apiKey === "string" && apiKey.trim().length > 0) {
1328
+ return;
1329
+ }
1330
+ throw new WorkspaceNotSelectedError();
1172
1331
  };
1173
- const createAgent = async (payload) => {
1174
- const res = await doFetch(`${base}/agents`, {
1332
+ const postJson = async (url, payload) => {
1333
+ requireWorkspace();
1334
+ const res = await doFetch(url, {
1175
1335
  method: "POST",
1176
1336
  body: JSON.stringify(payload),
1177
1337
  headers: jsonHeaders
1178
1338
  });
1179
1339
  return res.json();
1180
1340
  };
1181
- const forkAgentFromTemplate = async (payload) => {
1182
- const res = await doFetch(`${base}/agents/from-template`, {
1341
+ const postWithSse = async (url, payload, callbacks) => {
1342
+ requireWorkspace();
1343
+ const headers = buildHeaders({ "content-type": "application/json" });
1344
+ const fx = cfg.fetchImpl ?? fetch;
1345
+ const res = await fx(url, {
1183
1346
  method: "POST",
1184
1347
  body: JSON.stringify(payload),
1185
- headers: jsonHeaders
1348
+ headers
1186
1349
  });
1187
- return res.json();
1188
- };
1189
- const updateAgent = async (agentId, payload) => {
1190
- const res = await doFetch(`${base}/agents/${agentId}`, {
1191
- method: "PATCH",
1192
- body: JSON.stringify(payload),
1193
- headers: jsonHeaders
1194
- });
1195
- return res.json();
1350
+ if (!res.ok) {
1351
+ const body = await res.text();
1352
+ throw new Error(`POST ${url} failed with status ${res.status}: ${body}`);
1353
+ }
1354
+ const contentType = res.headers.get("content-type") ?? "";
1355
+ if (contentType.includes("application/json")) {
1356
+ const agent = await res.json();
1357
+ callbacks.onAgentCreated?.(agent);
1358
+ return agent;
1359
+ }
1360
+ return consumeSseStream(
1361
+ res,
1362
+ buildSseHandlers(callbacks),
1363
+ "agent-created"
1364
+ );
1196
1365
  };
1197
- const resolveAgentId = (agent) => {
1198
- return typeof agent === "string" ? agent : agent.agentId;
1366
+ const getWithSse = async (url, callbacks) => {
1367
+ requireWorkspace();
1368
+ const headers = buildHeaders({});
1369
+ const fx = cfg.fetchImpl ?? fetch;
1370
+ const res = await fx(url, { method: "GET", headers });
1371
+ if (!res.ok) {
1372
+ const body = await res.text();
1373
+ throw new Error(`GET ${url} failed with status ${res.status}: ${body}`);
1374
+ }
1375
+ const contentType = res.headers.get("content-type") ?? "";
1376
+ if (contentType.includes("application/json")) {
1377
+ const agent = await res.json();
1378
+ callbacks.onAgentCreated?.(agent);
1379
+ return agent;
1380
+ }
1381
+ return consumeSseStream(
1382
+ res,
1383
+ buildSseHandlers(callbacks),
1384
+ "agent"
1385
+ );
1199
1386
  };
1200
- const deleteAgent = async (agent) => {
1201
- const agentId = resolveAgentId(agent);
1202
- await doFetch(`${base}/agents/${agentId}`, {
1203
- method: "DELETE"
1387
+ const fetchPage = async (options = {}) => {
1388
+ requireWorkspace();
1389
+ const query = serializeListOptions({
1390
+ page: options.page,
1391
+ limit: options.limit,
1392
+ filter: options.filter
1204
1393
  });
1394
+ const res = await doFetch(`${base}/agents`, { method: "GET", query });
1395
+ return res.json();
1205
1396
  };
1206
1397
  const baseApi = {
1207
- list: listAgents,
1208
- get: getAgentDetail,
1209
- create: createAgent,
1210
- forkFromTemplate: forkAgentFromTemplate,
1211
- update: updateAgent,
1212
- delete: deleteAgent
1398
+ async list(options = {}) {
1399
+ const opts = { ...options ?? {} };
1400
+ const response = await fetchPage(opts);
1401
+ return attachPaginator(response, fetchPage, opts);
1402
+ },
1403
+ async get(agentId, callbacks) {
1404
+ if (callbacks) {
1405
+ return getWithSse(`${base}/agents/${agentId}`, callbacks);
1406
+ }
1407
+ requireWorkspace();
1408
+ const res = await doFetch(`${base}/agents/${agentId}`, { method: "GET" });
1409
+ const contentType = res.headers.get("content-type") ?? "";
1410
+ if (contentType.includes("text/event-stream")) {
1411
+ return consumeSseStream(
1412
+ res,
1413
+ buildSseHandlers({}),
1414
+ "agent",
1415
+ {
1416
+ resolveImmediately: true
1417
+ }
1418
+ );
1419
+ }
1420
+ return res.json();
1421
+ },
1422
+ async create(payload, callbacks) {
1423
+ if (callbacks) {
1424
+ return postWithSse(`${base}/agents`, payload, callbacks);
1425
+ }
1426
+ return postJson(`${base}/agents`, payload);
1427
+ },
1428
+ async clone(agentId, payload) {
1429
+ return postJson(
1430
+ `${base}/agents/${agentId}/clone`,
1431
+ buildCloneRequest(payload)
1432
+ );
1433
+ },
1434
+ async forkFromTemplate(payload, callbacks) {
1435
+ if (callbacks) {
1436
+ return postWithSse(`${base}/agents/from-template`, payload, callbacks);
1437
+ }
1438
+ return postJson(`${base}/agents/from-template`, payload);
1439
+ },
1440
+ async rebuild(agentId, callbacks) {
1441
+ if (callbacks) {
1442
+ return postWithSse(`${base}/agents/${agentId}/rebuild`, {}, callbacks);
1443
+ }
1444
+ return postJson(`${base}/agents/${agentId}/rebuild`, {});
1445
+ },
1446
+ async update(agentId, payload) {
1447
+ requireWorkspace();
1448
+ const res = await doFetch(`${base}/agents/${agentId}`, {
1449
+ method: "PATCH",
1450
+ body: JSON.stringify(payload),
1451
+ headers: jsonHeaders
1452
+ });
1453
+ return res.json();
1454
+ },
1455
+ async delete(agent) {
1456
+ requireWorkspace();
1457
+ await doFetch(`${base}/agents/${resolveAgentId(agent)}`, {
1458
+ method: "DELETE"
1459
+ });
1460
+ }
1213
1461
  };
1214
1462
  if (!relatedApis) {
1215
1463
  return baseApi;
1216
1464
  }
1465
+ return withEntityWrapping(baseApi, fetchPage, relatedApis);
1466
+ }
1467
+ function withEntityWrapping(api, fetchPage, deps) {
1217
1468
  const wrapAgent = (detail) => createAgentEntity(detail, {
1218
- tagsApi: relatedApis.tagsApi,
1219
- phonesApi: relatedApis.phonesApi,
1220
- scheduleApi: relatedApis.scheduleApi,
1221
- scheduleExceptionsApi: relatedApis.scheduleExceptionsApi,
1222
- versionsApi: relatedApis.versionsApi,
1223
- blueprintsApi: relatedApis.blueprintsApi,
1224
- stagesApi: relatedApis.stagesApi,
1225
- stageTriggersApi: relatedApis.stageTriggersApi,
1469
+ ...deps,
1226
1470
  reload: async (agentId) => {
1227
- const latest = await getAgentDetail(agentId);
1471
+ const latest = await api.get(agentId);
1228
1472
  return wrapAgent(latest);
1229
1473
  },
1230
1474
  updateAgent: async (agentId, payload) => {
1231
- const updated = await updateAgent(agentId, payload);
1475
+ const updated = await api.update(agentId, payload);
1232
1476
  return wrapAgent(updated);
1233
1477
  },
1234
1478
  deleteAgent: async (agentId) => {
1235
- await deleteAgent(agentId);
1479
+ await api.delete(agentId);
1480
+ },
1481
+ cloneAgent: async (agentId, payload) => {
1482
+ const cloned = await api.clone(agentId, payload);
1483
+ return wrapAgent(cloned);
1236
1484
  }
1237
1485
  });
1486
+ const wrapList = async (opts) => {
1487
+ const result = await fetchPage(opts);
1488
+ const items = Array.isArray(result.data) ? result.data : [];
1489
+ return { ...result, data: items.map(wrapAgent) };
1490
+ };
1238
1491
  return {
1239
- ...baseApi,
1492
+ ...api,
1240
1493
  async list(options = {}) {
1241
- const normalizedOptions = { ...options ?? {} };
1242
- const applyWrap = async (opts) => {
1243
- const result = await fetchAgentsPage(opts);
1244
- const items = Array.isArray(result.data) ? result.data : [];
1245
- return {
1246
- ...result,
1247
- data: items.map((summary) => wrapAgent(summary))
1248
- };
1249
- };
1250
- const initial = await applyWrap(normalizedOptions);
1251
- return attachPaginator(initial, applyWrap, normalizedOptions);
1494
+ const opts = { ...options ?? {} };
1495
+ const initial = await wrapList(opts);
1496
+ return attachPaginator(initial, wrapList, opts);
1252
1497
  },
1253
- async get(agentId) {
1254
- const detail = await getAgentDetail(agentId);
1255
- return wrapAgent(detail);
1498
+ async get(agentId, callbacks) {
1499
+ return wrapAgent(await api.get(agentId, callbacks));
1256
1500
  },
1257
- async create(payload) {
1258
- const detail = await createAgent(payload);
1259
- return wrapAgent(detail);
1501
+ async create(payload, callbacks) {
1502
+ return wrapAgent(await api.create(payload, callbacks));
1260
1503
  },
1261
- async forkFromTemplate(payload) {
1262
- const detail = await forkAgentFromTemplate(payload);
1263
- return wrapAgent(detail);
1504
+ async clone(agentId, payload) {
1505
+ return wrapAgent(await api.clone(agentId, payload));
1506
+ },
1507
+ async forkFromTemplate(payload, callbacks) {
1508
+ return wrapAgent(await api.forkFromTemplate(payload, callbacks));
1264
1509
  },
1265
1510
  async update(agentId, payload) {
1266
- const detail = await updateAgent(agentId, payload);
1267
- return wrapAgent(detail);
1511
+ return wrapAgent(await api.update(agentId, payload));
1268
1512
  }
1269
1513
  };
1270
1514
  }
@@ -1300,6 +1544,82 @@ function createApiKeysApi(cfg) {
1300
1544
  };
1301
1545
  }
1302
1546
 
1547
+ // src/api/billing.ts
1548
+ function createBillingApi(cfg) {
1549
+ const { base, doFetch } = createHttp(cfg);
1550
+ return {
1551
+ async getBalance() {
1552
+ const res = await doFetch(`${base}/billing/balance`, {
1553
+ method: "GET"
1554
+ });
1555
+ return res.json();
1556
+ }
1557
+ };
1558
+ }
1559
+
1560
+ // src/api/calls.ts
1561
+ function createCallsApi(cfg) {
1562
+ const { base, doFetch } = createHttp(cfg);
1563
+ const fetchCallsPage = async (options = {}) => {
1564
+ const {
1565
+ agentBatchId,
1566
+ agentId,
1567
+ executionId,
1568
+ recordedAfter,
1569
+ recordedBefore,
1570
+ durationBucket,
1571
+ goalStatus,
1572
+ query: searchQuery,
1573
+ ...listOptions
1574
+ } = options ?? {};
1575
+ const query = serializeListOptions(listOptions, {
1576
+ agentBatchId,
1577
+ agentId,
1578
+ executionId,
1579
+ recordedAfter,
1580
+ recordedBefore,
1581
+ durationBucket,
1582
+ goalStatus,
1583
+ query: searchQuery
1584
+ });
1585
+ const res = await doFetch(`${base}/calls`, {
1586
+ method: "GET",
1587
+ query
1588
+ });
1589
+ return res.json();
1590
+ };
1591
+ return {
1592
+ async list(options = {}) {
1593
+ const normalizedOptions = { ...options ?? {} };
1594
+ const response = await fetchCallsPage(normalizedOptions);
1595
+ return attachPaginator(response, fetchCallsPage, normalizedOptions);
1596
+ },
1597
+ async stream(options) {
1598
+ const query = buildSearchParams([
1599
+ ["after", options.after],
1600
+ ["limit", options.limit],
1601
+ ["agentBatchId", options.agentBatchId],
1602
+ ["agentId", options.agentId],
1603
+ ["executionId", options.executionId],
1604
+ ["durationBucket", options.durationBucket],
1605
+ ["goalStatus", options.goalStatus],
1606
+ ["query", options.query]
1607
+ ]);
1608
+ const res = await doFetch(`${base}/calls/stream`, {
1609
+ method: "GET",
1610
+ query
1611
+ });
1612
+ return res.json();
1613
+ },
1614
+ async get(callId) {
1615
+ const res = await doFetch(`${base}/calls/${callId}`, {
1616
+ method: "GET"
1617
+ });
1618
+ return res.json();
1619
+ }
1620
+ };
1621
+ }
1622
+
1303
1623
  // src/api/campaigns.ts
1304
1624
  function createCampaignsApi(cfg) {
1305
1625
  const { base, doFetch } = createHttp(cfg);
@@ -1315,10 +1635,7 @@ function createCampaignsApi(cfg) {
1315
1635
  return res.json();
1316
1636
  };
1317
1637
  const fetchExecutionsPage = async (campaignId, options = {}) => {
1318
- const query = serializeListOptions({
1319
- page: options.page,
1320
- limit: options.limit
1321
- });
1638
+ const query = serializeListOptions(options ?? {});
1322
1639
  const res = await doFetch(`${base}/campaigns/${campaignId}/executions`, {
1323
1640
  method: "GET",
1324
1641
  query
@@ -1372,6 +1689,51 @@ function createCampaignsApi(cfg) {
1372
1689
  const response = await fetchExecutionsPage(campaignId, normalizedOptions);
1373
1690
  const fetchPage = (opts) => fetchExecutionsPage(campaignId, opts);
1374
1691
  return attachPaginator(response, fetchPage, normalizedOptions);
1692
+ },
1693
+ /**
1694
+ * Pausa una campaña en curso. Los reintentos ya programados se
1695
+ * reagendan al ejecutarse (sin consumir intentos) hasta `resume()`.
1696
+ */
1697
+ async pause(campaignId) {
1698
+ const res = await doFetch(`${base}/campaigns/${campaignId}/pause`, {
1699
+ method: "POST"
1700
+ });
1701
+ return res.json();
1702
+ },
1703
+ /**
1704
+ * Reanuda una campaña pausada. Re-encola los reintentos pendientes
1705
+ * según su `nextRetryAt`.
1706
+ */
1707
+ async resume(campaignId) {
1708
+ const res = await doFetch(`${base}/campaigns/${campaignId}/resume`, {
1709
+ method: "POST"
1710
+ });
1711
+ return res.json();
1712
+ },
1713
+ /**
1714
+ * Cancela definitivamente una campaña no terminal. Los reintentos
1715
+ * pendientes se descartan — operación destructiva.
1716
+ */
1717
+ async cancel(campaignId) {
1718
+ const res = await doFetch(`${base}/campaigns/${campaignId}/cancel`, {
1719
+ method: "POST"
1720
+ });
1721
+ return res.json();
1722
+ },
1723
+ /**
1724
+ * Descarga el CSV con todas las ejecuciones de la campaña. Devuelve un
1725
+ * `Blob` con `text/csv; charset=utf-8` (BOM UTF-8 incluido). Para
1726
+ * campañas > 20,000 filas la API responde 413.
1727
+ */
1728
+ async exportExecutions(campaignId) {
1729
+ const res = await doFetch(
1730
+ `${base}/campaigns/${campaignId}/executions/export`,
1731
+ {
1732
+ method: "GET",
1733
+ headers: { Accept: "text/csv" }
1734
+ }
1735
+ );
1736
+ return res.blob();
1375
1737
  }
1376
1738
  };
1377
1739
  }
@@ -1452,6 +1814,70 @@ function createCatalogsApi(cfg) {
1452
1814
  };
1453
1815
  }
1454
1816
 
1817
+ // src/api/documents.ts
1818
+ function createDocumentsApi(cfg) {
1819
+ const { base, doFetch, resolveWorkspaceId, resolveApiKey } = createHttp(cfg);
1820
+ const jsonHeaders = { "content-type": "application/json" };
1821
+ const requireWorkspace = () => {
1822
+ const workspaceId = resolveWorkspaceId();
1823
+ if (typeof workspaceId === "string" && workspaceId.trim().length > 0) {
1824
+ return;
1825
+ }
1826
+ const apiKey = resolveApiKey();
1827
+ if (typeof apiKey === "string" && apiKey.trim().length > 0) {
1828
+ return;
1829
+ }
1830
+ throw new WorkspaceNotSelectedError();
1831
+ };
1832
+ return {
1833
+ async create(files) {
1834
+ requireWorkspace();
1835
+ const res = await doFetch(`${base}/documents`, {
1836
+ method: "POST",
1837
+ body: JSON.stringify({ files }),
1838
+ headers: jsonHeaders
1839
+ });
1840
+ return res.json();
1841
+ }
1842
+ };
1843
+ }
1844
+
1845
+ // src/api/sip-trunks.ts
1846
+ function createSipTrunksApi(cfg) {
1847
+ const { base, doFetch } = createHttp(cfg);
1848
+ return {
1849
+ async list() {
1850
+ const res = await doFetch(`${base}/sip/trunks`, { method: "GET" });
1851
+ return res.json();
1852
+ },
1853
+ async get(trunkId) {
1854
+ const res = await doFetch(`${base}/sip/trunks/${trunkId}`, {
1855
+ method: "GET"
1856
+ });
1857
+ return res.json();
1858
+ },
1859
+ async create(body) {
1860
+ const res = await doFetch(`${base}/sip/trunks`, {
1861
+ method: "POST",
1862
+ headers: { "Content-Type": "application/json" },
1863
+ body: JSON.stringify(body)
1864
+ });
1865
+ return res.json();
1866
+ },
1867
+ async update(trunkId, body) {
1868
+ const res = await doFetch(`${base}/sip/trunks/${trunkId}`, {
1869
+ method: "PATCH",
1870
+ headers: { "Content-Type": "application/json" },
1871
+ body: JSON.stringify(body)
1872
+ });
1873
+ return res.json();
1874
+ },
1875
+ async delete(trunkId) {
1876
+ await doFetch(`${base}/sip/trunks/${trunkId}`, { method: "DELETE" });
1877
+ }
1878
+ };
1879
+ }
1880
+
1455
1881
  // src/api/tools.ts
1456
1882
  var IDEMPOTENCY_HEADER = "Idempotency-Key";
1457
1883
  var generateIdempotencyKey = (explicit) => {
@@ -1520,7 +1946,15 @@ function createToolsApi(cfg) {
1520
1946
  });
1521
1947
  return res.json();
1522
1948
  };
1523
- return {
1949
+ const fetchToolConnectionsPage = async (options = {}) => {
1950
+ const query = serializeListOptions(options ?? {});
1951
+ const res = await doFetch(`${base}/tools/connections`, {
1952
+ method: "GET",
1953
+ query
1954
+ });
1955
+ return res.json();
1956
+ };
1957
+ const api = {
1524
1958
  async list(options = {}) {
1525
1959
  const normalizedOptions = { ...options ?? {} };
1526
1960
  const response = await fetchToolsPage(normalizedOptions);
@@ -1534,6 +1968,17 @@ function createToolsApi(cfg) {
1534
1968
  const response = await fetchPage(normalizedOptions);
1535
1969
  return attachPaginator(response, fetchPage, normalizedOptions);
1536
1970
  },
1971
+ async listConnections(options = {}) {
1972
+ const normalizedOptions = {
1973
+ ...options ?? {}
1974
+ };
1975
+ const response = await fetchToolConnectionsPage(normalizedOptions);
1976
+ return attachPaginator(
1977
+ response,
1978
+ fetchToolConnectionsPage,
1979
+ normalizedOptions
1980
+ );
1981
+ },
1537
1982
  async uploadResource(toolId, payload) {
1538
1983
  const formData = toFormData(payload);
1539
1984
  const res = await doFetch(`${base}/tools/${toolId}/resources`, {
@@ -1579,8 +2024,115 @@ function createToolsApi(cfg) {
1579
2024
  body: JSON.stringify(payload)
1580
2025
  });
1581
2026
  return res.json();
2027
+ },
2028
+ async createConnection(payload, options = {}) {
2029
+ const idempotencyKey = generateIdempotencyKey(options.idempotencyKey);
2030
+ const res = await doFetch(`${base}/tools/connections`, {
2031
+ method: "POST",
2032
+ headers: {
2033
+ ...jsonHeaders,
2034
+ [IDEMPOTENCY_HEADER]: idempotencyKey
2035
+ },
2036
+ body: JSON.stringify(payload)
2037
+ });
2038
+ return res.json();
2039
+ },
2040
+ async executeConnection(toolAgentConnectionId, payload, options = {}) {
2041
+ const idempotencyKey = generateIdempotencyKey(options.idempotencyKey);
2042
+ const res = await doFetch(
2043
+ `${base}/tools/connections/${toolAgentConnectionId}/execute`,
2044
+ {
2045
+ method: "POST",
2046
+ headers: {
2047
+ ...jsonHeaders,
2048
+ [IDEMPOTENCY_HEADER]: idempotencyKey
2049
+ },
2050
+ body: JSON.stringify(payload)
2051
+ }
2052
+ );
2053
+ return res.json();
1582
2054
  }
1583
2055
  };
2056
+ const connections = {
2057
+ connect: api.connect,
2058
+ create: api.createConnection,
2059
+ execute: api.executeConnection,
2060
+ list: api.listConnections,
2061
+ createConnection: api.createConnection,
2062
+ executeConnection: api.executeConnection
2063
+ };
2064
+ return {
2065
+ ...api,
2066
+ connections
2067
+ };
2068
+ }
2069
+
2070
+ // src/api/usage.ts
2071
+ var import_api_query_builder = require("@getsupervisor/api-query-builder");
2072
+ function createUsageApi(cfg) {
2073
+ const { base, doFetch } = createHttp(cfg);
2074
+ const fetchUsageAgentsPage = async (options = {}) => {
2075
+ const { resource, from, to, ...listOptions } = options;
2076
+ const query = serializeListOptions({
2077
+ ...listOptions,
2078
+ filter: resolveFilter(
2079
+ buildUsageFilter(resource, from, to),
2080
+ listOptions.filter
2081
+ )
2082
+ });
2083
+ const res = await doFetch(`${base}/usage/agents`, {
2084
+ method: "GET",
2085
+ query
2086
+ });
2087
+ return res.json();
2088
+ };
2089
+ return {
2090
+ async agents(options = {}) {
2091
+ const normalizedOptions = {
2092
+ ...options
2093
+ };
2094
+ const response = await fetchUsageAgentsPage(normalizedOptions);
2095
+ return attachPaginator(response, fetchUsageAgentsPage, normalizedOptions);
2096
+ }
2097
+ };
2098
+ }
2099
+ function resolveFilter(usageFilter, fallback) {
2100
+ if (usageFilter) {
2101
+ return usageFilter;
2102
+ }
2103
+ return fallback;
2104
+ }
2105
+ function appendCondition(query, factory) {
2106
+ if (query) {
2107
+ query.and(factory);
2108
+ return query;
2109
+ }
2110
+ return new import_api_query_builder.Query(factory);
2111
+ }
2112
+ var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
2113
+ function toISOString(value) {
2114
+ const input = DATE_ONLY.test(value) ? `${value}T00:00:00` : value;
2115
+ const date = new Date(input);
2116
+ if (Number.isNaN(date.getTime())) {
2117
+ return value;
2118
+ }
2119
+ return date.toISOString();
2120
+ }
2121
+ function buildUsageFilter(resource, from, to) {
2122
+ let query;
2123
+ if (resource) {
2124
+ query = appendCondition(query, (qb) => qb.eq("resource", resource));
2125
+ }
2126
+ if (from) {
2127
+ query = appendCondition(
2128
+ query,
2129
+ (qb) => qb.mte("createdAt", toISOString(from))
2130
+ );
2131
+ }
2132
+ if (to) {
2133
+ query = appendCondition(query, (qb) => qb.lt("createdAt", toISOString(to)));
2134
+ }
2135
+ return query;
1584
2136
  }
1585
2137
 
1586
2138
  // src/utils/catalog-voices.ts
@@ -1641,9 +2193,9 @@ function pickGender(value) {
1641
2193
  }
1642
2194
 
1643
2195
  // src/utils/catalog-filter.ts
1644
- var import_api_query_builder = require("@getsupervisor/api-query-builder");
2196
+ var import_api_query_builder2 = require("@getsupervisor/api-query-builder");
1645
2197
  function createCatalogTypeQuery(type) {
1646
- return new import_api_query_builder.Query((qb) => qb.eq("type", type));
2198
+ return new import_api_query_builder2.Query((qb) => qb.eq("type", type));
1647
2199
  }
1648
2200
  function ensureCatalogTypeFilter(filter, type) {
1649
2201
  const requiredQuery = createCatalogTypeQuery(type);
@@ -1879,6 +2431,35 @@ function createWebhooksApi(cfg) {
1879
2431
  `${base}/webhooks/${webhookId}/subscriptions/${subscriptionId}`,
1880
2432
  { method: "DELETE" }
1881
2433
  );
2434
+ },
2435
+ // Deliveries
2436
+ async listDeliveries(webhookId, options = {}) {
2437
+ const fetchPage = async (opts) => {
2438
+ const query = serializeListOptions({
2439
+ page: opts.page,
2440
+ limit: opts.limit,
2441
+ sort: opts.sort,
2442
+ fields: opts.fields,
2443
+ include: opts.include,
2444
+ search: opts.search,
2445
+ filter: opts.filter
2446
+ });
2447
+ const res = await doFetch(`${base}/webhooks/${webhookId}/deliveries`, {
2448
+ method: "GET",
2449
+ query
2450
+ });
2451
+ return res.json();
2452
+ };
2453
+ const normalized = { ...options ?? {} };
2454
+ const response = await fetchPage(normalized);
2455
+ return attachPaginator(response, fetchPage, normalized);
2456
+ },
2457
+ async getDelivery(webhookId, deliveryId) {
2458
+ const res = await doFetch(
2459
+ `${base}/webhooks/${webhookId}/deliveries/${deliveryId}`,
2460
+ { method: "GET" }
2461
+ );
2462
+ return res.json();
1882
2463
  }
1883
2464
  };
1884
2465
  }
@@ -1887,6 +2468,26 @@ function createWebhooksApi(cfg) {
1887
2468
  function createWorkspacesApi(cfg) {
1888
2469
  const { base, doFetch } = createHttp(cfg);
1889
2470
  const jsonHeaders = { "content-type": "application/json" };
2471
+ const fetchWorkspacesPage = async (options = {}) => {
2472
+ const normalized = { ...options ?? {} };
2473
+ const query = serializeListOptions({
2474
+ page: normalized.page,
2475
+ limit: normalized.limit,
2476
+ sort: normalized.sort,
2477
+ fields: normalized.fields,
2478
+ include: normalized.include,
2479
+ search: normalized.search,
2480
+ filter: normalized.filter,
2481
+ or: normalized.or
2482
+ });
2483
+ const headers = normalized.refreshCache ? { "X-Cache-Refresh": "true" } : void 0;
2484
+ const res = await doFetch(`${base}/workspaces`, {
2485
+ method: "GET",
2486
+ query,
2487
+ headers
2488
+ });
2489
+ return res.json();
2490
+ };
1890
2491
  const fetchPhonesPage = async (workspaceId, opts = {}) => {
1891
2492
  const { channel } = opts ?? {};
1892
2493
  const query = serializeListOptions(
@@ -1909,6 +2510,11 @@ function createWorkspacesApi(cfg) {
1909
2510
  return res.json();
1910
2511
  };
1911
2512
  return {
2513
+ async list(options = {}) {
2514
+ const normalizedOptions = { ...options ?? {} };
2515
+ const response = await fetchWorkspacesPage(normalizedOptions);
2516
+ return attachPaginator(response, fetchWorkspacesPage, normalizedOptions);
2517
+ },
1912
2518
  async listPhones(workspaceId, opts = {}) {
1913
2519
  const normalizedOptions = {
1914
2520
  ...opts ?? {}
@@ -1917,8 +2523,8 @@ function createWorkspacesApi(cfg) {
1917
2523
  const fetchPage = (options) => fetchPhonesPage(workspaceId, options);
1918
2524
  return attachPaginator(response, fetchPage, normalizedOptions);
1919
2525
  },
1920
- async enable(workspaceId, payload) {
1921
- const res = await doFetch(`${base}/workspaces/${workspaceId}/enable`, {
2526
+ async enable(payload) {
2527
+ const res = await doFetch(`${base}/workspaces/enable`, {
1922
2528
  method: "POST",
1923
2529
  headers: jsonHeaders,
1924
2530
  body: JSON.stringify(payload)
@@ -1964,6 +2570,7 @@ function createClient(initialCfg) {
1964
2570
  const stagesApi = createAgentStagesApi(runtimeCfg);
1965
2571
  const voicesApi = createVoicesApi(runtimeCfg);
1966
2572
  const apiKeysApi = createApiKeysApi(runtimeCfg);
2573
+ const callsApi = createCallsApi(runtimeCfg);
1967
2574
  const catalogsApi = createCatalogsApi(runtimeCfg);
1968
2575
  const catalogTemplatesApi = createCatalogTemplatesApi(runtimeCfg);
1969
2576
  const webhooksApi = createWebhooksApi(runtimeCfg);
@@ -2032,9 +2639,14 @@ function createClient(initialCfg) {
2032
2639
  ...catalogsApi,
2033
2640
  templates: catalogTemplatesApi
2034
2641
  },
2642
+ documents: createDocumentsApi(runtimeCfg),
2035
2643
  campaigns: createCampaignsApi(runtimeCfg),
2036
2644
  voices: voicesApi,
2037
2645
  apiKeys: apiKeysApi,
2646
+ billing: createBillingApi(runtimeCfg),
2647
+ calls: callsApi,
2648
+ usage: createUsageApi(runtimeCfg),
2649
+ sip: createSipTrunksApi(runtimeCfg),
2038
2650
  webhooks: webhooksApi
2039
2651
  };
2040
2652
  return {
@@ -2097,6 +2709,7 @@ function createClient(initialCfg) {
2097
2709
  HttpError,
2098
2710
  NetworkError,
2099
2711
  TimeoutError,
2712
+ WorkspaceNotSelectedError,
2100
2713
  bindAgentBlueprints,
2101
2714
  bindAgentPhones,
2102
2715
  bindAgentSchedule,
@@ -2117,14 +2730,21 @@ function createClient(initialCfg) {
2117
2730
  createAgentVersionsApi,
2118
2731
  createAgentsApi,
2119
2732
  createApiKeysApi,
2733
+ createBillingApi,
2734
+ createCallsApi,
2120
2735
  createCampaignsApi,
2121
2736
  createCatalogTemplatesApi,
2122
2737
  createCatalogsApi,
2123
2738
  createClient,
2739
+ createDocumentsApi,
2124
2740
  createHttp,
2741
+ createSipTrunksApi,
2125
2742
  createToolsApi,
2743
+ createUsageApi,
2126
2744
  createVoicesApi,
2127
2745
  createWebhooksApi,
2128
- createWorkspacesApi
2746
+ createWorkspacesApi,
2747
+ isApiErrorBody,
2748
+ isApiHttpError
2129
2749
  });
2130
2750
  //# sourceMappingURL=index.cjs.map