@zorveus/sdk 0.1.9 → 0.2.1

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.js CHANGED
@@ -22,6 +22,7 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  APIConnectionError: () => APIConnectionError,
24
24
  APIStatusError: () => APIStatusError,
25
+ AppConnectionNotFoundError: () => AppConnectionNotFoundError,
25
26
  AuthenticationError: () => AuthenticationError,
26
27
  CapExceededError: () => CapExceededError,
27
28
  CreditGrantExpiredError: () => CreditGrantExpiredError,
@@ -29,7 +30,9 @@ __export(index_exports, {
29
30
  InternalServerError: () => InternalServerError,
30
31
  NotFoundError: () => NotFoundError,
31
32
  PermissionDeniedError: () => PermissionDeniedError,
33
+ ProductUserAllowanceInsufficientError: () => ProductUserAllowanceInsufficientError,
32
34
  RateLimitError: () => RateLimitError,
35
+ ReservationConflictError: () => ReservationConflictError,
33
36
  UnprocessableEntityError: () => UnprocessableEntityError,
34
37
  Zorveus: () => Zorveus,
35
38
  ZorveusBusinessError: () => ZorveusBusinessError,
@@ -39,8 +42,12 @@ __export(index_exports, {
39
42
  ZorveusServiceClient: () => ZorveusServiceClient,
40
43
  assertDecimalString: () => assertDecimalString,
41
44
  createAPIError: () => createAPIError,
45
+ decimalPercentage: () => decimalPercentage,
46
+ formatDecimalString: () => formatDecimalString,
42
47
  formatGatewayMetadata: () => formatGatewayMetadata,
43
- isValidDecimalString: () => isValidDecimalString
48
+ isValidDecimalString: () => isValidDecimalString,
49
+ normalInputTokens: () => normalInputTokens,
50
+ parseZorveusGatewayError: () => parseZorveusGatewayError
44
51
  });
45
52
  module.exports = __toCommonJS(index_exports);
46
53
 
@@ -73,6 +80,7 @@ var ZorveusError = class extends Error {
73
80
  code;
74
81
  param;
75
82
  type;
83
+ params;
76
84
  headers;
77
85
  rawBody;
78
86
  constructor(message, options = {}) {
@@ -82,6 +90,7 @@ var ZorveusError = class extends Error {
82
90
  this.code = options.code;
83
91
  this.param = options.param;
84
92
  this.type = options.type;
93
+ this.params = options.params;
85
94
  this.headers = options.headers;
86
95
  this.rawBody = options.rawBody;
87
96
  if (options.cause) {
@@ -149,27 +158,71 @@ var ZorveusBusinessError = class extends APIStatusError {
149
158
  };
150
159
  var InsufficientFundsError = class extends ZorveusBusinessError {
151
160
  constructor(message = "Wallet balance exhausted. Top up required.", options = {}) {
152
- super(message, { ...options, status: options.status ?? 402, code: options.code ?? "insufficient_funds" });
161
+ super(message, {
162
+ ...options,
163
+ status: options.status ?? 402,
164
+ code: options.code ?? "zorveus_reservation_insufficient_balance"
165
+ });
153
166
  this.name = "InsufficientFundsError";
154
167
  }
155
168
  };
156
169
  var CapExceededError = class extends ZorveusBusinessError {
157
170
  constructor(message = "Spending cap limit reached", options = {}) {
158
- super(message, { ...options, status: options.status ?? 402, code: options.code ?? "cap_exceeded" });
171
+ super(message, {
172
+ ...options,
173
+ status: options.status ?? 403,
174
+ code: options.code ?? "zorveus_cap_exceeded"
175
+ });
159
176
  this.name = "CapExceededError";
160
177
  }
161
178
  };
179
+ var ProductUserAllowanceInsufficientError = class extends ZorveusBusinessError {
180
+ constructor(message = "Product user AI allowance is insufficient for this request.", options = {}) {
181
+ super(message, {
182
+ ...options,
183
+ status: options.status ?? 403,
184
+ code: options.code ?? "zorveus_product_user_allowance_insufficient",
185
+ params: options.params
186
+ });
187
+ this.name = "ProductUserAllowanceInsufficientError";
188
+ }
189
+ };
162
190
  var CreditGrantExpiredError = class extends ZorveusBusinessError {
163
191
  constructor(message = "Product user credit grant has expired", options = {}) {
164
- super(message, { ...options, status: options.status ?? 403, code: options.code ?? "credit_grant_expired" });
192
+ super(message, {
193
+ ...options,
194
+ status: options.status ?? 403,
195
+ code: options.code ?? "credit_grant_expired"
196
+ });
165
197
  this.name = "CreditGrantExpiredError";
166
198
  }
167
199
  };
200
+ var AppConnectionNotFoundError = class extends ZorveusBusinessError {
201
+ constructor(message = "Inference key or app connection not found or revoked", options = {}) {
202
+ super(message, {
203
+ ...options,
204
+ status: options.status ?? 403,
205
+ code: options.code ?? "zorveus_app_connection_not_found"
206
+ });
207
+ this.name = "AppConnectionNotFoundError";
208
+ }
209
+ };
210
+ var ReservationConflictError = class extends ZorveusBusinessError {
211
+ constructor(message = "Idempotency key reused with conflicting request parameters", options = {}) {
212
+ super(message, {
213
+ ...options,
214
+ status: options.status ?? 409,
215
+ code: options.code ?? "zorveus_reservation_conflict"
216
+ });
217
+ this.name = "ReservationConflictError";
218
+ }
219
+ };
168
220
  function createAPIError(status, body, headers) {
169
221
  let message = `Request failed with status ${status}`;
170
222
  let code;
171
223
  let param;
172
224
  let type;
225
+ let params;
173
226
  let parsedBody = body;
174
227
  if (typeof body === "string") {
175
228
  try {
@@ -187,29 +240,62 @@ function createAPIError(status, body, headers) {
187
240
  }
188
241
  if (parsedBody && typeof parsedBody === "object") {
189
242
  const obj = parsedBody;
190
- if (obj.error && typeof obj.error === "object") {
243
+ const providerFields = obj.provider_specific_fields ?? obj.error?.provider_specific_fields;
244
+ const nestedGatewayError = providerFields?.error ?? providerFields;
245
+ if (nestedGatewayError && typeof nestedGatewayError === "object") {
246
+ if (typeof nestedGatewayError.message === "string") message = nestedGatewayError.message;
247
+ if (typeof nestedGatewayError.code === "string") code = nestedGatewayError.code;
248
+ if (typeof nestedGatewayError.param === "string") param = nestedGatewayError.param;
249
+ if (typeof nestedGatewayError.type === "string") type = nestedGatewayError.type;
250
+ if (nestedGatewayError.params && typeof nestedGatewayError.params === "object") {
251
+ params = nestedGatewayError.params;
252
+ }
253
+ } else if (obj.error && typeof obj.error === "object") {
191
254
  const err = obj.error;
192
255
  if (typeof err.message === "string") message = err.message;
193
256
  if (typeof err.code === "string") code = err.code;
194
257
  if (typeof err.param === "string") param = err.param;
195
258
  if (typeof err.type === "string") type = err.type;
196
- } else if (typeof obj.detail === "string") {
197
- message = obj.detail;
198
- } else if (Array.isArray(obj.detail) && obj.detail.length > 0) {
199
- const first = obj.detail[0];
200
- if (first && typeof first.msg === "string") {
201
- message = first.msg;
259
+ if (err.params && typeof err.params === "object") {
260
+ params = err.params;
261
+ }
262
+ } else {
263
+ if (typeof obj.message === "string") message = obj.message;
264
+ if (typeof obj.code === "string") code = obj.code;
265
+ if (typeof obj.param === "string") param = obj.param;
266
+ if (typeof obj.type === "string") type = obj.type;
267
+ if (obj.params && typeof obj.params === "object") {
268
+ params = obj.params;
269
+ }
270
+ if (typeof obj.detail === "string") {
271
+ message = obj.detail;
272
+ } else if (Array.isArray(obj.detail) && obj.detail.length > 0) {
273
+ const first = obj.detail[0];
274
+ if (first && typeof first.msg === "string") {
275
+ message = first.msg;
276
+ }
202
277
  }
203
- } else if (typeof obj.message === "string") {
204
- message = obj.message;
205
278
  }
206
279
  }
207
- const options = { status, code, param, type, headers, rawBody: body };
280
+ const options = { status, code, param, type, params, headers, rawBody: body };
208
281
  const normalizedCode = (code || "").toLowerCase();
209
- if (normalizedCode.includes("cap_exceed") || normalizedCode.includes("spend_cap") || message.toLowerCase().includes("spending cap")) {
282
+ if (normalizedCode === "zorveus_product_user_allowance_insufficient" || normalizedCode === "zorveus_product_user_credits_insufficient" || normalizedCode.includes("allowance_insufficient") || normalizedCode.includes("credits_insufficient") || message.toLowerCase().includes("allowance remaining")) {
283
+ return new ProductUserAllowanceInsufficientError(message, {
284
+ ...options,
285
+ status: status === 200 ? 403 : status,
286
+ params
287
+ });
288
+ }
289
+ if (normalizedCode === "zorveus_cap_exceeded" || normalizedCode.includes("cap_exceed") || normalizedCode.includes("spend_cap") || message.toLowerCase().includes("spending cap")) {
210
290
  return new CapExceededError(message, options);
211
291
  }
212
- if (normalizedCode.includes("insufficient_funds") || normalizedCode.includes("balance_exhausted") || normalizedCode.includes("insufficient_balance") || normalizedCode.includes("wallet_empty") || message.toLowerCase().includes("insufficient funds") || message.toLowerCase().includes("balance exhausted") || message.toLowerCase().includes("wallet is empty")) {
292
+ if (normalizedCode === "zorveus_app_connection_not_found" || normalizedCode.includes("app_connection_not_found")) {
293
+ return new AppConnectionNotFoundError(message, options);
294
+ }
295
+ if (status === 409 || normalizedCode === "zorveus_reservation_conflict" || normalizedCode.includes("reservation_conflict")) {
296
+ return new ReservationConflictError(message, options);
297
+ }
298
+ if (status === 402 || normalizedCode === "zorveus_reservation_insufficient_balance" || normalizedCode.includes("insufficient_funds") || normalizedCode.includes("balance_exhausted") || normalizedCode.includes("insufficient_balance") || normalizedCode.includes("wallet_empty") || message.toLowerCase().includes("insufficient funds") || message.toLowerCase().includes("balance exhausted") || message.toLowerCase().includes("wallet is empty")) {
213
299
  return new InsufficientFundsError(message, options);
214
300
  }
215
301
  if (normalizedCode.includes("grant_expired")) {
@@ -218,9 +304,6 @@ function createAPIError(status, body, headers) {
218
304
  if (status === 401) {
219
305
  return new AuthenticationError(message, options);
220
306
  }
221
- if (status === 402) {
222
- return new InsufficientFundsError(message, options);
223
- }
224
307
  if (status === 403) {
225
308
  return new PermissionDeniedError(message, options);
226
309
  }
@@ -238,6 +321,22 @@ function createAPIError(status, body, headers) {
238
321
  }
239
322
  return new APIStatusError(message, options);
240
323
  }
324
+ function parseZorveusGatewayError(error) {
325
+ if (error instanceof ZorveusError) {
326
+ return error;
327
+ }
328
+ if (!error || typeof error !== "object") {
329
+ return error;
330
+ }
331
+ const errObj = error;
332
+ const status = typeof errObj.status === "number" ? errObj.status : typeof errObj.statusCode === "number" ? errObj.statusCode : void 0;
333
+ const rawBody = errObj.error ?? errObj.body ?? errObj.rawBody;
334
+ if (status !== void 0 && rawBody !== void 0) {
335
+ const headers = errObj.headers && typeof errObj.headers === "object" ? errObj.headers : void 0;
336
+ return createAPIError(status, rawBody, headers);
337
+ }
338
+ return error;
339
+ }
241
340
 
242
341
  // src/http/transport.ts
243
342
  var HTTPTransport = class {
@@ -482,6 +581,9 @@ function formatGatewayMetadata(meta) {
482
581
  if (meta.externalUserId) {
483
582
  result.external_user_id = meta.externalUserId;
484
583
  }
584
+ if (meta.productEndUserId) {
585
+ result.product_end_user_id = meta.productEndUserId;
586
+ }
485
587
  if (meta.displayName !== void 0 || meta.userEmail !== void 0 || meta.metadata !== void 0) {
486
588
  result.product_user = {
487
589
  display_name: meta.displayName ?? null,
@@ -538,6 +640,17 @@ var Chat = class {
538
640
  }
539
641
  };
540
642
 
643
+ // src/types/usage-events.ts
644
+ function normalInputTokens(event) {
645
+ if (event.cache_usage_breakdown_status !== "reported" || event.input_tokens === null) {
646
+ return null;
647
+ }
648
+ return Math.max(
649
+ 0,
650
+ event.input_tokens - event.cache_read_input_tokens - event.cache_creation_input_tokens - event.cache_creation_1h_input_tokens
651
+ );
652
+ }
653
+
541
654
  // src/resources/embeddings.ts
542
655
  var Embeddings = class {
543
656
  transport;
@@ -649,9 +762,6 @@ function isValidDecimalString(value) {
649
762
  return decimalRegex.test(trimmed);
650
763
  }
651
764
  function assertDecimalString(value, fieldName) {
652
- if (typeof value === "number") {
653
- return value.toFixed(4);
654
- }
655
765
  if (isValidDecimalString(value)) {
656
766
  return value.trim();
657
767
  }
@@ -659,6 +769,36 @@ function assertDecimalString(value, fieldName) {
659
769
  `Field '${fieldName}' must be a valid decimal string (e.g. "15.0000"), received: ${JSON.stringify(value)}`
660
770
  );
661
771
  }
772
+ function formatDecimalString(value, fractionDigits = 2) {
773
+ const decimal = assertDecimalString(value, "value");
774
+ if (!Number.isInteger(fractionDigits) || fractionDigits < 0) {
775
+ throw new RangeError("fractionDigits must be a non-negative integer");
776
+ }
777
+ const negative = decimal.startsWith("-");
778
+ const unsigned = negative ? decimal.slice(1) : decimal;
779
+ const [integer, fraction = ""] = unsigned.split(".");
780
+ const roundedInput = fraction.padEnd(fractionDigits + 1, "0");
781
+ let scaled = BigInt(integer + roundedInput.slice(0, fractionDigits).padEnd(fractionDigits, "0"));
782
+ if (Number(roundedInput[fractionDigits] ?? "0") >= 5) scaled += 1n;
783
+ const digits = scaled.toString().padStart(fractionDigits + 1, "0");
784
+ const formatted = fractionDigits === 0 ? digits : `${digits.slice(0, -fractionDigits)}.${digits.slice(-fractionDigits)}`;
785
+ return negative && scaled !== 0n ? `-${formatted}` : formatted;
786
+ }
787
+ function decimalPercentage(numerator, denominator) {
788
+ const toScaledInteger = (value, scale) => {
789
+ const [integer, fraction = ""] = assertDecimalString(value, "value").split(".");
790
+ return BigInt(integer + fraction.padEnd(scale, "0").slice(0, scale));
791
+ };
792
+ const fractionDigits = Math.max(
793
+ numerator.split(".")[1]?.length ?? 0,
794
+ denominator.split(".")[1]?.length ?? 0
795
+ );
796
+ const top = toScaledInteger(numerator, fractionDigits);
797
+ const bottom = toScaledInteger(denominator, fractionDigits);
798
+ if (bottom <= 0n) return 0;
799
+ const basisPoints = top * 10000n / bottom;
800
+ return Number(basisPoints) / 100;
801
+ }
662
802
 
663
803
  // src/resources/product-users.ts
664
804
  var ProductUsers = class {
@@ -751,6 +891,7 @@ var ProductUsers = class {
751
891
  async list(params = {}, options = {}) {
752
892
  const query = {};
753
893
  if (params.orgId) query.org_id = params.orgId;
894
+ if (params.appId) query.app_id = params.appId;
754
895
  if (params.limit !== void 0) query.limit = params.limit;
755
896
  if (params.offset !== void 0) query.offset = params.offset;
756
897
  return this.transport.request("/product-users", {
@@ -874,12 +1015,13 @@ var ProviderCredentials = class {
874
1015
  this.transport = transport;
875
1016
  }
876
1017
  /**
877
- * Registers an organization BYOK provider credential via Service Key (`POST /provider-credentials/org-programmatic`).
1018
+ * Registers an organization BYOK provider credential via Service Key (`POST /provider-credentials`).
878
1019
  */
879
1020
  async create(params, options = {}) {
880
1021
  const payload = {
881
1022
  provider: params.provider,
882
1023
  credential_name: params.credentialName,
1024
+ secret: params.apiKey,
883
1025
  api_key: params.apiKey,
884
1026
  secret_kind: params.secretKind || "api_key",
885
1027
  model_policies: params.modelPolicies || [],
@@ -899,7 +1041,7 @@ var ProviderCredentials = class {
899
1041
  );
900
1042
  }
901
1043
  /**
902
- * Lists BYOK provider credentials for an organization (`GET /provider-credentials/org-programmatic`).
1044
+ * Lists BYOK provider credentials for an organization (`GET /provider-credentials`).
903
1045
  */
904
1046
  async list(params = {}, options = {}) {
905
1047
  const query = {};
@@ -914,6 +1056,13 @@ var ProviderCredentials = class {
914
1056
  }
915
1057
  );
916
1058
  }
1059
+ /** Retrieves one BYOK provider credential by ID. */
1060
+ async get(providerCredentialId, options = {}) {
1061
+ return this.transport.request(
1062
+ `/provider-credentials/org-programmatic/${encodeURIComponent(providerCredentialId)}`,
1063
+ { method: "GET", ...options }
1064
+ );
1065
+ }
917
1066
  /**
918
1067
  * Rotates a provider credential secret (`POST /provider-credentials/org-programmatic/{id}/rotate`).
919
1068
  */
@@ -959,10 +1108,40 @@ var ProviderCredentials = class {
959
1108
  }
960
1109
  };
961
1110
 
1111
+ // src/resources/usage-events.ts
1112
+ var UsageEvents = class {
1113
+ constructor(transport) {
1114
+ this.transport = transport;
1115
+ }
1116
+ transport;
1117
+ /** Lists immutable usage events with cursor pagination. */
1118
+ async list(params = {}, options = {}) {
1119
+ return this.transport.request("/dashboard-api/usage/events", {
1120
+ method: "GET",
1121
+ query: {
1122
+ org_id: params.orgId,
1123
+ app_id: params.appId,
1124
+ app_connection_id: params.appConnectionId,
1125
+ product_end_user_id: params.productEndUserId,
1126
+ model: params.model,
1127
+ provider: params.provider,
1128
+ billing_mode: params.billingMode,
1129
+ status: params.status,
1130
+ created_after: params.createdAfter,
1131
+ created_before: params.createdBefore,
1132
+ limit: params.limit,
1133
+ cursor: params.cursor
1134
+ },
1135
+ ...options
1136
+ });
1137
+ }
1138
+ };
1139
+
962
1140
  // src/service-client.ts
963
1141
  var ZorveusServiceClient = class {
964
1142
  productUsers;
965
1143
  providerCredentials;
1144
+ usageEvents;
966
1145
  transport;
967
1146
  constructor(options) {
968
1147
  if (!options || !options.apiKey) {
@@ -981,6 +1160,7 @@ var ZorveusServiceClient = class {
981
1160
  });
982
1161
  this.productUsers = new ProductUsers(this.transport);
983
1162
  this.providerCredentials = new ProviderCredentials(this.transport);
1163
+ this.usageEvents = new UsageEvents(this.transport);
984
1164
  }
985
1165
  };
986
1166
 
@@ -1182,6 +1362,7 @@ var ZorveusOAuth = class {
1182
1362
  0 && (module.exports = {
1183
1363
  APIConnectionError,
1184
1364
  APIStatusError,
1365
+ AppConnectionNotFoundError,
1185
1366
  AuthenticationError,
1186
1367
  CapExceededError,
1187
1368
  CreditGrantExpiredError,
@@ -1189,7 +1370,9 @@ var ZorveusOAuth = class {
1189
1370
  InternalServerError,
1190
1371
  NotFoundError,
1191
1372
  PermissionDeniedError,
1373
+ ProductUserAllowanceInsufficientError,
1192
1374
  RateLimitError,
1375
+ ReservationConflictError,
1193
1376
  UnprocessableEntityError,
1194
1377
  Zorveus,
1195
1378
  ZorveusBusinessError,
@@ -1199,7 +1382,11 @@ var ZorveusOAuth = class {
1199
1382
  ZorveusServiceClient,
1200
1383
  assertDecimalString,
1201
1384
  createAPIError,
1385
+ decimalPercentage,
1386
+ formatDecimalString,
1202
1387
  formatGatewayMetadata,
1203
- isValidDecimalString
1388
+ isValidDecimalString,
1389
+ normalInputTokens,
1390
+ parseZorveusGatewayError
1204
1391
  });
1205
1392
  //# sourceMappingURL=index.js.map