@limitry/cli 1.0.0-rc.16 → 1.0.0-rc.19

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/limitry.mjs CHANGED
@@ -23,6 +23,10 @@ var brand_default = {
23
23
  labs: ["lab"],
24
24
  statusPage: true,
25
25
  discordInvite: "https://discord.gg/Nb6QFd6ER4",
26
+ shortLinks: {
27
+ "/linkedin": { source: "linkedin", medium: "social" },
28
+ "/youtube": { source: "youtube", medium: "video" }
29
+ },
26
30
  profiles: { x: "limitryhq", github: "limitry" },
27
31
  summary: "Limitry is the limits, credits and budgets layer for the software you build: give each of your users, teams, tenants, API keys or agents an allowance, and before any costly request one call tells your code whether it may happen.",
28
32
  expectedAssets: [
@@ -102,9 +106,14 @@ var brand_default = {
102
106
  emailSignUp: "button"
103
107
  },
104
108
  devPortOffset: 100,
109
+ appShortcuts: [
110
+ { name: "Usage", url: "/usage" },
111
+ { name: "Limits", url: "/limits" }
112
+ ],
105
113
  social: {
106
114
  background: "#F6F8FB"
107
- }
115
+ },
116
+ tagline: "Limits, credits and budgets for the software you build"
108
117
  };
109
118
 
110
119
  // src/brand/index.ts
@@ -166,6 +175,8 @@ var brand = {
166
175
  ].filter(Boolean),
167
176
  /** One sentence: what the product is — llms.txt and the agent skill lead with it. */
168
177
  summary: optional.summary ?? `${brand_default.productName} documentation and API.`,
178
+ /** A short line under the logo in the site's footer (the home page's headline); none without it. */
179
+ tagline: optional.tagline,
169
180
  /** Where vulnerability reports go — /.well-known/security.txt and /security publish it. Defaults to security@<domain>. */
170
181
  securityContact: optional.securityContact ?? `security@${brand_default.domain}`,
171
182
  /** Where the Contact form's help topics go (Question, Bug, Billing). Never shown on a page. Defaults to support@<domain>. */
@@ -228,21 +239,21 @@ var signInOptions = {
228
239
  emailSignUp: optional.signIn?.emailSignUp ?? "form"
229
240
  };
230
241
  function resolveProductEnvironments(environments, defaultEnvironment, docs) {
231
- const list = (environments ?? []).map((env) => ({
242
+ const list2 = (environments ?? []).map((env) => ({
232
243
  name: env.name,
233
244
  keyPrefix: env.keyPrefix,
234
245
  readOnlyWorkspace: env.readOnlyWorkspace ?? false,
235
246
  description: env.description ?? "",
236
247
  agentLabel: env.agentLabel ?? env.description ?? ""
237
248
  }));
238
- const names = new Set(list.map((env) => env.name));
239
- const prefixes = new Set(list.map((env) => env.keyPrefix));
240
- if (names.size !== list.length || prefixes.size !== list.length) {
249
+ const names = new Set(list2.map((env) => env.name));
250
+ const prefixes = new Set(list2.map((env) => env.keyPrefix));
251
+ if (names.size !== list2.length || prefixes.size !== list2.length) {
241
252
  throw new Error(
242
253
  "brand.json environments: each needs its own name and keyPrefix"
243
254
  );
244
255
  }
245
- for (const env of list) {
256
+ for (const env of list2) {
246
257
  if (!/^[a-z][a-z0-9-]*$/.test(env.name)) {
247
258
  throw new Error(`brand.json environment name "${env.name}" is invalid`);
248
259
  }
@@ -263,9 +274,9 @@ function resolveProductEnvironments(environments, defaultEnvironment, docs) {
263
274
  );
264
275
  }
265
276
  return {
266
- list,
267
- default: defaultEnvironment ?? list[0]?.name ?? null,
268
- docs: list.length > 0 ? docs ?? null : null
277
+ list: list2,
278
+ default: defaultEnvironment ?? list2[0]?.name ?? null,
279
+ docs: list2.length > 0 ? docs ?? null : null
269
280
  };
270
281
  }
271
282
  var productEnvironments = resolveProductEnvironments(
@@ -759,42 +770,269 @@ function removeTrailingSlash(url) {
759
770
  }
760
771
 
761
772
  // node_modules/@limitry/sdk/dist/errors.js
762
- var ApiError = class extends Error {
773
+ var BASE_ERROR_NAME = `${brand2.name.split(/[-_]/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("")}Error`;
774
+ var SdkError = class _SdkError extends Error {
775
+ constructor(message, options) {
776
+ super(message, options);
777
+ this.name = new.target === _SdkError ? BASE_ERROR_NAME : new.target.name;
778
+ }
779
+ };
780
+ var APIConnectionError = class extends SdkError {
781
+ constructor(options = {}) {
782
+ super(options.message ?? "Could not connect to the API", {
783
+ cause: options.cause
784
+ });
785
+ }
786
+ };
787
+ var APITimeoutError = class extends APIConnectionError {
788
+ constructor(options = {}) {
789
+ super({ message: "The request timed out", cause: options.cause });
790
+ }
791
+ };
792
+ var APIError = class extends SdkError {
793
+ /** The HTTP status code. */
763
794
  status;
795
+ /** The error's code, to branch on (`not_found`, `rate_limited`, …). */
764
796
  code;
797
+ /** The request's id: quote it to support. */
765
798
  requestId;
766
- constructor(status, code2, message, requestId) {
767
- super(message);
768
- this.name = "ApiError";
769
- this.status = status;
770
- this.code = code2;
771
- this.requestId = requestId;
799
+ /**
800
+ * The response's headers (Retry-After, Server-Timing, the rate-limit
801
+ * ones): empty when the error was not built from a response.
802
+ */
803
+ headers;
804
+ /** What is wrong with each field, when the API refused the input. */
805
+ details;
806
+ /** A link to the error's entry in the docs. */
807
+ docs;
808
+ constructor(init) {
809
+ super(init.message);
810
+ this.status = init.status;
811
+ this.code = init.code;
812
+ this.requestId = init.requestId;
813
+ this.headers = init.headers ?? new Headers();
814
+ this.details = init.details;
815
+ this.docs = init.docs;
772
816
  }
773
817
  };
818
+ var BadRequestError = class extends APIError {
819
+ };
820
+ var AuthenticationError = class extends APIError {
821
+ };
822
+ var PlanLimitError = class extends APIError {
823
+ };
824
+ var PermissionDeniedError = class extends APIError {
825
+ };
826
+ var NotFoundError = class extends APIError {
827
+ };
828
+ var ConflictError = class extends APIError {
829
+ };
830
+ var UnprocessableEntityError = class extends APIError {
831
+ };
832
+ var RateLimitError = class extends APIError {
833
+ };
834
+ var InternalServerError = class extends APIError {
835
+ };
836
+ var BY_STATUS = {
837
+ 400: BadRequestError,
838
+ 401: AuthenticationError,
839
+ 402: PlanLimitError,
840
+ 403: PermissionDeniedError,
841
+ 404: NotFoundError,
842
+ 409: ConflictError,
843
+ 422: UnprocessableEntityError,
844
+ 429: RateLimitError
845
+ };
846
+ function errorClassFor(status) {
847
+ return BY_STATUS[status] ?? (status >= 500 ? InternalServerError : APIError);
848
+ }
774
849
  function apiErrorFrom(error, response) {
775
- const envelope = error ?? {};
776
- return new ApiError(response.status, envelope.error?.code ?? "http_error", envelope.error?.message ?? `HTTP ${response.status}`, envelope.error?.requestId);
850
+ const envelope = error !== null && typeof error === "object" ? error : {};
851
+ const body = envelope.error ?? {};
852
+ const ErrorClass = errorClassFor(response.status);
853
+ return new ErrorClass({
854
+ status: response.status,
855
+ code: body.code ?? "http_error",
856
+ message: body.message ?? `HTTP ${response.status}`,
857
+ requestId: body.requestId ?? response.headers.get("x-request-id") ?? void 0,
858
+ headers: response.headers,
859
+ ...Array.isArray(body.details) ? { details: body.details } : {},
860
+ ...typeof body.docs === "string" ? { docs: body.docs } : {}
861
+ });
862
+ }
863
+ function connectionErrorFrom(error, signal) {
864
+ if (signal?.aborted)
865
+ return signal.reason;
866
+ if (error instanceof SdkError)
867
+ return error;
868
+ if (error instanceof Error && error.name === "TimeoutError") {
869
+ return new APITimeoutError({ cause: error });
870
+ }
871
+ return new APIConnectionError({ cause: error });
872
+ }
873
+ function withConnectionErrors(fetch2) {
874
+ return async (request) => {
875
+ try {
876
+ return await fetch2(request);
877
+ } catch (error) {
878
+ throw connectionErrorFrom(error, request.signal);
879
+ }
880
+ };
777
881
  }
778
882
 
779
883
  // node_modules/@limitry/sdk/dist/product/index.js
780
884
  var product_exports = {};
781
885
  __export(product_exports, {
782
- LimitReached: () => LimitReached,
783
- Unavailable: () => Unavailable,
886
+ LimitReachedError: () => LimitReachedError,
887
+ UnavailableError: () => UnavailableError,
784
888
  createLimits: () => createLimits,
785
889
  productMethods: () => productMethods,
786
890
  productRetry: () => productRetry2
787
891
  });
788
892
 
893
+ // node_modules/@limitry/sdk/dist/pagination.js
894
+ var Page = class {
895
+ /** This page's items. */
896
+ items;
897
+ /** The cursor for the next page; null on the last one. */
898
+ nextCursor;
899
+ #next;
900
+ constructor(body, next) {
901
+ Object.assign(this, body);
902
+ this.items = body.items;
903
+ this.nextCursor = body.nextCursor ?? null;
904
+ this.#next = next;
905
+ }
906
+ /** Whether another page follows this one. */
907
+ hasNextPage() {
908
+ return this.#next !== null && typeof this.nextCursor === "string";
909
+ }
910
+ /** The next page; throws when this is the last one (see hasNextPage). */
911
+ getNextPage() {
912
+ if (!this.hasNextPage()) {
913
+ return Promise.reject(new Error("No next page: check hasNextPage() first"));
914
+ }
915
+ return this.#next(this.nextCursor);
916
+ }
917
+ /** This page and every page after it. */
918
+ async *iterPages() {
919
+ yield this;
920
+ let page = this.hasNextPage() ? await this.getNextPage() : null;
921
+ while (page) {
922
+ yield page;
923
+ page = page.hasNextPage() ? await page.getNextPage() : null;
924
+ }
925
+ }
926
+ /** Every item, from this page on, fetching each next page as it goes. */
927
+ async *[Symbol.asyncIterator]() {
928
+ for await (const page of this.iterPages())
929
+ yield* page.items;
930
+ }
931
+ };
932
+ var PagePromise = class {
933
+ #page;
934
+ [Symbol.toStringTag] = "PagePromise";
935
+ constructor(page) {
936
+ this.#page = page;
937
+ }
938
+ then(onFulfilled, onRejected) {
939
+ return this.#page.then(onFulfilled, onRejected);
940
+ }
941
+ catch(onRejected) {
942
+ return this.#page.catch(onRejected);
943
+ }
944
+ finally(onFinally) {
945
+ return this.#page.finally(onFinally);
946
+ }
947
+ async *[Symbol.asyncIterator]() {
948
+ yield* await this.#page;
949
+ }
950
+ };
951
+ function pages(fetch2, paged) {
952
+ const load = (cursor) => new PagePromise(fetch2(cursor).then((body) => new Page(body, paged ? load : null)));
953
+ return load(void 0);
954
+ }
955
+
956
+ // node_modules/@limitry/sdk/dist/resources.js
957
+ var TIMEOUT_HEADER = "x-sdk-timeout";
958
+ async function call(client, op, pathParams, input, options = {}, content) {
959
+ const query = {};
960
+ const body = {};
961
+ for (const [name, value] of Object.entries(input ?? {})) {
962
+ if (value === void 0)
963
+ continue;
964
+ (op.query.includes(name) ? query : body)[name] = value;
965
+ }
966
+ const headers = {
967
+ ...options.headers,
968
+ ...options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {},
969
+ ...options.timeout === void 0 ? {} : { [TIMEOUT_HEADER]: String(options.timeout) }
970
+ };
971
+ const request = client.request;
972
+ const raw = op.rawBody ? content instanceof Blob ? content : new Blob([content]) : void 0;
973
+ const { data, error, response } = await request(op.method, op.path, {
974
+ params: { path: pathParams, query },
975
+ ...op.hasBody ? { body } : {},
976
+ ...raw ? {
977
+ body: raw,
978
+ bodySerializer: (value) => value,
979
+ headers: { "content-type": raw.type || op.rawBody, ...headers }
980
+ } : { headers },
981
+ ...op.rawResponse ? { parseAs: "blob" } : {},
982
+ signal: options.signal
983
+ });
984
+ if (error !== void 0 || !response.ok) {
985
+ throw apiErrorFrom(error, response);
986
+ }
987
+ return data;
988
+ }
989
+ function list(client, op, pathParams, input, options = {}, paged = true) {
990
+ return pages((cursor) => call(client, op, pathParams, cursor === void 0 ? input : { ...input, cursor }, options), paged);
991
+ }
992
+
789
993
  // node_modules/@limitry/sdk/dist/retry.js
790
994
  var WRITES = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
791
995
  var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
792
996
  var DEFAULT_MAX_RETRIES = 2;
793
- var MAX_WAIT_MS = 2e4;
997
+ var MAX_WAIT_MS = 6e4;
794
998
  var MAX_BASE_KEY = 200;
795
999
  var PRODUCT_RETRY_HEADER = "x-sdk-product-retry";
1000
+ var DEFAULT_TIMEOUT_MS = 6e4;
1001
+ function withAttemptTimeout(fetch2, ms) {
1002
+ return (request) => {
1003
+ const asked = Number(request.headers.get(TIMEOUT_HEADER));
1004
+ const limit = asked > 0 ? asked : ms;
1005
+ const headers = new Headers(request.headers);
1006
+ headers.delete(TIMEOUT_HEADER);
1007
+ return fetch2(new Request(request, {
1008
+ headers,
1009
+ signal: AbortSignal.any([
1010
+ request.signal,
1011
+ AbortSignal.timeout(Math.max(1, Math.round(limit)))
1012
+ ])
1013
+ }));
1014
+ };
1015
+ }
796
1016
  var productRetry = () => "productRetry" in product_exports ? Reflect.get(product_exports, "productRetry") ?? null : null;
797
1017
  var wait = (ms) => new Promise((done) => setTimeout(done, ms));
1018
+ function pause(sleep, ms, signal) {
1019
+ if (signal.aborted)
1020
+ return Promise.reject(signal.reason);
1021
+ return new Promise((done, fail) => {
1022
+ const abort = () => fail(signal.reason);
1023
+ signal.addEventListener("abort", abort, { once: true });
1024
+ sleep(ms).then(() => {
1025
+ signal.removeEventListener("abort", abort);
1026
+ if (signal.aborted)
1027
+ fail(signal.reason);
1028
+ else
1029
+ done();
1030
+ }, (error) => {
1031
+ signal.removeEventListener("abort", abort);
1032
+ fail(error);
1033
+ });
1034
+ });
1035
+ }
798
1036
  function backoff(attempt) {
799
1037
  const base = Math.min(500 * 2 ** attempt, 8e3);
800
1038
  return base * (0.75 + Math.random() * 0.25);
@@ -857,7 +1095,7 @@ function withRetries(fetch2, options = {}) {
857
1095
  } catch (error) {
858
1096
  if (last || request.signal.aborted)
859
1097
  throw error;
860
- await sleep(backoff(attempt));
1098
+ await pause(sleep, backoff(attempt), request.signal);
861
1099
  continue;
862
1100
  }
863
1101
  const laterMs = later ? await later.wait(response, laterTries) : null;
@@ -868,7 +1106,7 @@ function withRetries(fetch2, options = {}) {
868
1106
  laterTries++;
869
1107
  laterWaited += laterMs;
870
1108
  await response.body?.cancel();
871
- await sleep(laterMs);
1109
+ await pause(sleep, laterMs, request.signal);
872
1110
  attempt--;
873
1111
  continue;
874
1112
  }
@@ -878,7 +1116,7 @@ function withRetries(fetch2, options = {}) {
878
1116
  if (delay > MAX_WAIT_MS)
879
1117
  return response;
880
1118
  await response.body?.cancel();
881
- await sleep(delay);
1119
+ await pause(sleep, delay, request.signal);
882
1120
  }
883
1121
  };
884
1122
  }
@@ -947,43 +1185,76 @@ function checkedCost(units) {
947
1185
  }
948
1186
  return units;
949
1187
  }
950
- var LimitReached = class extends Error {
1188
+ var LimitReachedError = class extends SdkError {
951
1189
  reason;
952
1190
  /** The limit that refused; null for too many open reservations. */
953
1191
  limitId;
1192
+ limitName;
954
1193
  retryAfterSeconds;
955
1194
  decision;
956
1195
  constructor(decision) {
957
1196
  super(decision.reason?.message ?? "Refused");
958
- this.name = "LimitReached";
1197
+ this.name = "LimitReachedError";
959
1198
  this.reason = decision.reason?.code ?? "limit_reached";
960
1199
  this.limitId = decision.reason?.limitId ?? null;
1200
+ this.limitName = decision.reason?.limitName ?? null;
961
1201
  this.retryAfterSeconds = decision.retryAfterSeconds ?? null;
962
1202
  this.decision = decision;
963
1203
  }
964
1204
  };
965
- var Unavailable = class extends Error {
966
- constructor() {
967
- super("Limitry could not be reached and a limit refuses when unreachable");
968
- this.name = "Unavailable";
1205
+ var UnavailableError = class extends SdkError {
1206
+ reason;
1207
+ constructor(reason, options) {
1208
+ super(`Limitry gave no decision (${reason}) and a limit refuses when unreachable`, options);
1209
+ this.name = "UnavailableError";
1210
+ this.reason = reason;
1211
+ }
1212
+ };
1213
+ var NoDecision = class {
1214
+ // Plain fields, not parameter properties: Node's type stripping (the
1215
+ // docs build and the Python parity check import this file) refuses them.
1216
+ reason;
1217
+ cause;
1218
+ constructor(reason, cause) {
1219
+ this.reason = reason;
1220
+ this.cause = cause;
1221
+ }
1222
+ /** No answer in time: unlike an error, the check may have been decided. */
1223
+ get timedOut() {
1224
+ return this.reason === "timeout";
969
1225
  }
970
1226
  };
971
- var UNREACHABLE = /* @__PURE__ */ Symbol("unreachable");
972
- var TIMED_OUT = /* @__PURE__ */ Symbol("timed out");
973
1227
  var FINISH_TIMEOUT_MS = 5e3;
974
1228
  var wait2 = (ms) => new Promise((done) => setTimeout(done, ms));
1229
+ function abortable(work, signal) {
1230
+ if (!signal)
1231
+ return work;
1232
+ if (signal.aborted)
1233
+ return Promise.reject(signal.reason);
1234
+ return new Promise((resolve2, reject) => {
1235
+ const stop = () => reject(signal.reason);
1236
+ signal.addEventListener("abort", stop, { once: true });
1237
+ work.then((value) => {
1238
+ signal.removeEventListener("abort", stop);
1239
+ resolve2(value);
1240
+ }, (error) => {
1241
+ signal.removeEventListener("abort", stop);
1242
+ reject(error);
1243
+ });
1244
+ });
1245
+ }
975
1246
  function retryAfterMs(response) {
976
1247
  const value = response.headers.get("retry-after");
977
1248
  const seconds = value === null ? NaN : Number(value);
978
1249
  return Number.isFinite(seconds) ? seconds * 1e3 : void 0;
979
1250
  }
980
1251
  function createLimits(client, options = {}, internals = {}) {
981
- const timeoutMs = options.timeoutMs ?? 1500;
1252
+ const defaultTimeout = options.timeout ?? 1500;
982
1253
  const sleep = internals.sleep ?? wait2;
983
1254
  const random = internals.random ?? Math.random;
984
1255
  const remembered = /* @__PURE__ */ new Map();
985
1256
  const key = (s, action) => `${s.kind}\0${s.id}\0${action}`;
986
- const failMode = (s, action) => options.failMode ?? remembered.get(key(s, action)) ?? "open";
1257
+ const failMode = (r) => r.failMode ?? options.failMode ?? remembered.get(key(r.subject, r.action)) ?? "open";
987
1258
  const concurrentAmounts = /* @__PURE__ */ new Map();
988
1259
  const running = /* @__PURE__ */ new Map();
989
1260
  const remember = (s, action, decision) => {
@@ -996,15 +1267,13 @@ function createLimits(client, options = {}, internals = {}) {
996
1267
  } else {
997
1268
  concurrentAmounts.delete(key(s, action));
998
1269
  }
999
- if (options.failMode)
1000
- return;
1001
1270
  const closed = decision.limits.some((r) => r.failMode === "closed");
1002
1271
  remembered.set(key(s, action), closed ? "closed" : "open");
1003
1272
  if (remembered.size > 1e4) {
1004
1273
  remembered.delete(remembered.keys().next().value);
1005
1274
  }
1006
1275
  };
1007
- function budget(budgetMs) {
1276
+ function budget(budgetMs, signal) {
1008
1277
  const started = Date.now();
1009
1278
  let slept = 0;
1010
1279
  return {
@@ -1012,27 +1281,29 @@ function createLimits(client, options = {}, internals = {}) {
1012
1281
  left: () => Math.ceil(budgetMs - Math.max(Date.now() - started, slept)),
1013
1282
  async sleep(ms) {
1014
1283
  slept += ms;
1015
- await sleep(ms);
1284
+ await abortable(sleep(ms), signal);
1016
1285
  }
1017
1286
  };
1018
1287
  }
1019
- async function check(body, idempotencyKey, budgetMs = timeoutMs, finishOnly = false) {
1020
- const time = budget(budgetMs);
1288
+ async function check(body, idempotencyKey, budgetMs, finishOnly = false, signal) {
1289
+ const time = budget(budgetMs, signal);
1021
1290
  for (let tries = 0; ; tries++) {
1022
- const answer2 = await checkOnce(body, idempotencyKey, Math.max(1, time.left()), finishOnly);
1291
+ const answer2 = await checkOnce(body, idempotencyKey, Math.max(1, time.left()), finishOnly, signal);
1023
1292
  if (answer2.kind !== "later")
1024
1293
  return answer2.value;
1025
- const pause = retryWaitMs(answer2.retryAfterMs, tries, random);
1026
- if (pause >= time.left())
1027
- return UNREACHABLE;
1028
- await time.sleep(pause);
1294
+ const pause2 = retryWaitMs(answer2.retryAfterMs, tries, random);
1295
+ if (pause2 >= time.left())
1296
+ return new NoDecision("unreachable");
1297
+ await time.sleep(pause2);
1029
1298
  }
1030
1299
  }
1031
- async function checkOnce(body, idempotencyKey, wait3, finishOnly) {
1300
+ async function checkOnce(body, idempotencyKey, wait3, finishOnly, signal) {
1301
+ signal?.throwIfAborted();
1032
1302
  let timer;
1033
1303
  const late = new Promise((resolve2) => {
1034
- timer = setTimeout(() => resolve2(TIMED_OUT), wait3);
1304
+ timer = setTimeout(() => resolve2(new NoDecision("timeout")), wait3);
1035
1305
  });
1306
+ const deadline = AbortSignal.timeout(wait3);
1036
1307
  const asked = (async () => {
1037
1308
  try {
1038
1309
  const { data, error, response } = await client.POST("/checks", {
@@ -1044,25 +1315,27 @@ function createLimits(client, options = {}, internals = {}) {
1044
1315
  [PRODUCT_RETRY_HEADER]: "return",
1045
1316
  ...finishOnly ? { "limitry-finish-only": "1" } : {}
1046
1317
  },
1047
- signal: AbortSignal.timeout(wait3)
1318
+ signal: signal ? AbortSignal.any([deadline, signal]) : deadline
1048
1319
  });
1049
1320
  if (data)
1050
1321
  return data;
1051
1322
  if (isRetryLater(response, error))
1052
1323
  return { later: retryAfterMs(response) };
1053
- if (response.status === 402 || response.status === 429) {
1054
- return UNREACHABLE;
1055
- }
1056
- if (response.status < 500 && error) {
1057
- return new Error(`Limitry refused the check (${response.status}): ${JSON.stringify(error)}`);
1058
- }
1059
- return UNREACHABLE;
1324
+ if (response.status === 402)
1325
+ return new NoDecision("plan_limit_reached", apiErrorFrom(error, response));
1326
+ if (response.status === 429)
1327
+ return new NoDecision("rate_limited", apiErrorFrom(error, response));
1328
+ if (response.status < 500)
1329
+ return apiErrorFrom(error, response);
1330
+ return new NoDecision("unreachable", apiErrorFrom(error, response));
1060
1331
  } catch (error) {
1061
- return error?.name === "TimeoutError" ? TIMED_OUT : UNREACHABLE;
1332
+ if (signal?.aborted)
1333
+ throw signal.reason;
1334
+ return error?.name === "TimeoutError" || error instanceof APITimeoutError ? new NoDecision("timeout", error) : new NoDecision("unreachable", error);
1062
1335
  }
1063
1336
  })();
1064
1337
  try {
1065
- const answer2 = await Promise.race([asked, late]);
1338
+ const answer2 = await abortable(Promise.race([asked, late]), signal);
1066
1339
  if (answer2 instanceof Error)
1067
1340
  throw answer2;
1068
1341
  if (typeof answer2 === "object" && "later" in answer2)
@@ -1072,7 +1345,7 @@ function createLimits(client, options = {}, internals = {}) {
1072
1345
  clearTimeout(timer);
1073
1346
  }
1074
1347
  }
1075
- async function settle(id, action, cost) {
1348
+ async function settle(id, action, timeoutMs, cost) {
1076
1349
  const idempotencyKey = crypto.randomUUID();
1077
1350
  const time = budget(timeoutMs);
1078
1351
  for (let tries = 0; ; tries++) {
@@ -1101,10 +1374,10 @@ function createLimits(client, options = {}, internals = {}) {
1101
1374
  await time.sleep(retryMs);
1102
1375
  }
1103
1376
  }
1104
- async function releaseUnheard(body, idempotencyKey) {
1105
- const replay = await check(body, idempotencyKey);
1106
- if (typeof replay === "object" && replay.reservation) {
1107
- await settle(replay.reservation.id, "release");
1377
+ async function releaseUnheard(body, idempotencyKey, timeoutMs) {
1378
+ const replay = await check(body, idempotencyKey, timeoutMs);
1379
+ if (!(replay instanceof NoDecision) && replay.reservation) {
1380
+ await settle(replay.reservation.id, "release", timeoutMs);
1108
1381
  }
1109
1382
  }
1110
1383
  return {
@@ -1113,38 +1386,45 @@ function createLimits(client, options = {}, internals = {}) {
1113
1386
  * subjects): used, remaining, resetsAt — for showing an end user. Call
1114
1387
  * it from your server; a key never belongs in a browser. Not a check:
1115
1388
  * nothing is counted; a subject with no limit gets an empty `limits`.
1116
- * Throws on an error answer.
1389
+ * Throws the API's error (APIError) on an error answer.
1117
1390
  */
1118
1391
  async standing(request) {
1119
- const { data, error, response } = await client.GET("/usage/standing", {
1392
+ const { data, error, response } = await client.GET("/subjects/{subjectKind}/{subjectId}/standing", {
1120
1393
  params: {
1394
+ path: {
1395
+ subjectKind: request.subject.kind,
1396
+ subjectId: request.subject.id
1397
+ },
1121
1398
  query: {
1122
- subject: `${request.subject.kind}:${request.subject.id}`,
1123
1399
  ...request.shared?.length ? {
1124
1400
  shared: request.shared.map((s) => `${s.kind}:${s.id}`).join(",")
1125
1401
  } : {}
1126
1402
  }
1127
- }
1403
+ },
1404
+ ...request.signal ? { signal: request.signal } : {}
1128
1405
  });
1129
1406
  if (data)
1130
1407
  return data;
1131
- throw new Error(`Limitry refused usage.standing (${response.status}): ${JSON.stringify(error)}`);
1408
+ throw apiErrorFrom(error, response);
1132
1409
  },
1133
1410
  /** Checks `cost`, runs `fn` only if allowed, and returns its result. */
1134
1411
  async guard(request, fn) {
1412
+ request.signal?.throwIfAborted();
1135
1413
  const body = {
1136
1414
  subject: request.subject,
1137
1415
  shared: request.shared,
1138
1416
  action: request.action,
1139
1417
  cost: request.cost ?? 1
1140
1418
  };
1141
- const idempotencyKey = crypto.randomUUID();
1142
- const decision = await check(body, idempotencyKey);
1143
- if (decision === UNREACHABLE || decision === TIMED_OUT) {
1144
- if (failMode(request.subject, request.action) === "closed") {
1145
- throw new Unavailable();
1419
+ const idempotencyKey = request.idempotencyKey ?? crypto.randomUUID();
1420
+ const decision = await check(body, idempotencyKey, request.timeout ?? defaultTimeout, false, request.signal);
1421
+ if (decision instanceof NoDecision) {
1422
+ if (failMode(request) === "closed") {
1423
+ throw new UnavailableError(decision.reason, {
1424
+ cause: decision.cause
1425
+ });
1146
1426
  }
1147
- if (decision === TIMED_OUT) {
1427
+ if (decision.timedOut) {
1148
1428
  void check(body, idempotencyKey, FINISH_TIMEOUT_MS, true).catch(() => {
1149
1429
  });
1150
1430
  }
@@ -1152,7 +1432,7 @@ function createLimits(client, options = {}, internals = {}) {
1152
1432
  }
1153
1433
  remember(request.subject, request.action, decision);
1154
1434
  if (!decision.allowed)
1155
- throw new LimitReached(decision);
1435
+ throw new LimitReachedError(decision);
1156
1436
  return fn();
1157
1437
  },
1158
1438
  /**
@@ -1162,6 +1442,7 @@ function createLimits(client, options = {}, internals = {}) {
1162
1442
  * is taken for exactly as long as `fn` runs.
1163
1443
  */
1164
1444
  async reserve(request, fn) {
1445
+ request.signal?.throwIfAborted();
1165
1446
  const reserved = request.cost ?? 1;
1166
1447
  const body = {
1167
1448
  subject: request.subject,
@@ -1171,7 +1452,7 @@ function createLimits(client, options = {}, internals = {}) {
1171
1452
  mode: "reserve",
1172
1453
  ttlSeconds: request.ttlSeconds
1173
1454
  };
1174
- const idempotencyKey = crypto.randomUUID();
1455
+ const idempotencyKey = request.idempotencyKey ?? crypto.randomUUID();
1175
1456
  const slot = key(request.subject, request.action);
1176
1457
  const before = running.get(slot) ?? 0;
1177
1458
  running.set(slot, before + 1);
@@ -1188,7 +1469,16 @@ function createLimits(client, options = {}, internals = {}) {
1188
1469
  };
1189
1470
  async function reserveOnce(request, fn, body, idempotencyKey, before) {
1190
1471
  const reserved = request.cost ?? 1;
1191
- const decision = await check(body, idempotencyKey);
1472
+ const timeoutMs = request.timeout ?? defaultTimeout;
1473
+ let decision;
1474
+ try {
1475
+ decision = await check(body, idempotencyKey, timeoutMs, false, request.signal);
1476
+ } catch (error) {
1477
+ if (request.signal?.aborted)
1478
+ void releaseUnheard(body, idempotencyKey, timeoutMs).catch(() => {
1479
+ });
1480
+ throw error;
1481
+ }
1192
1482
  const uncounted = {
1193
1483
  // Checked even uncounted: the mistake shows whether or not
1194
1484
  // Limitry answered.
@@ -1196,13 +1486,14 @@ function createLimits(client, options = {}, internals = {}) {
1196
1486
  extend: async () => {
1197
1487
  }
1198
1488
  };
1199
- if (decision === UNREACHABLE || decision === TIMED_OUT) {
1200
- const unheard = () => decision === TIMED_OUT ? releaseUnheard(body, idempotencyKey) : Promise.resolve();
1489
+ if (decision instanceof NoDecision) {
1490
+ const none = decision;
1491
+ const unheard = () => none.timedOut ? releaseUnheard(body, idempotencyKey, timeoutMs) : Promise.resolve();
1201
1492
  const amount = concurrentAmounts.get(key(request.subject, request.action));
1202
- if (failMode(request.subject, request.action) === "closed" || // Open, but never past a concurrent limit's amount here.
1493
+ if (failMode(request) === "closed" || // Open, but never past a concurrent limit's amount here.
1203
1494
  amount !== void 0 && before >= amount) {
1204
1495
  await unheard();
1205
- throw new Unavailable();
1496
+ throw new UnavailableError(none.reason, { cause: none.cause });
1206
1497
  }
1207
1498
  try {
1208
1499
  return await fn(uncounted);
@@ -1212,7 +1503,7 @@ function createLimits(client, options = {}, internals = {}) {
1212
1503
  }
1213
1504
  remember(request.subject, request.action, decision);
1214
1505
  if (!decision.allowed || !decision.reservation) {
1215
- throw new LimitReached(decision);
1506
+ throw new LimitReachedError(decision);
1216
1507
  }
1217
1508
  const id = decision.reservation.id;
1218
1509
  let used = reserved;
@@ -1234,10 +1525,10 @@ function createLimits(client, options = {}, internals = {}) {
1234
1525
  try {
1235
1526
  result = await fn(reservation);
1236
1527
  } catch (error) {
1237
- await settle(id, "release");
1528
+ await settle(id, "release", timeoutMs);
1238
1529
  throw error;
1239
1530
  }
1240
- await settle(id, "commit", used);
1531
+ await settle(id, "commit", timeoutMs, used);
1241
1532
  return result;
1242
1533
  }
1243
1534
  }
@@ -1257,37 +1548,6 @@ var productMethods = (client) => {
1257
1548
  };
1258
1549
  var productRetry2 = movingRetry();
1259
1550
 
1260
- // node_modules/@limitry/sdk/dist/resources.js
1261
- async function call(client, op, pathParams, input, options = {}, content) {
1262
- const query = {};
1263
- const body = {};
1264
- for (const [name, value] of Object.entries(input ?? {})) {
1265
- if (value === void 0)
1266
- continue;
1267
- (op.query.includes(name) ? query : body)[name] = value;
1268
- }
1269
- const headers = {
1270
- ...options.headers,
1271
- ...options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}
1272
- };
1273
- const request = client.request;
1274
- const raw = op.rawBody ? content instanceof Blob ? content : new Blob([content]) : void 0;
1275
- const { data, error, response } = await request(op.method, op.path, {
1276
- params: { path: pathParams, query },
1277
- ...op.hasBody ? { body } : {},
1278
- ...raw ? {
1279
- body: raw,
1280
- bodySerializer: (value) => value,
1281
- headers: { "content-type": raw.type || op.rawBody, ...headers }
1282
- } : { headers },
1283
- ...op.rawResponse ? { parseAs: "blob" } : {}
1284
- });
1285
- if (error !== void 0 || !response.ok) {
1286
- throw apiErrorFrom(error, response);
1287
- }
1288
- return data;
1289
- }
1290
-
1291
1551
  // node_modules/@limitry/sdk/dist/resources.gen.js
1292
1552
  function resources(client) {
1293
1553
  return {
@@ -1295,6 +1555,10 @@ function resources(client) {
1295
1555
  create: (
1296
1556
  /** Check whether a subject may act */
1297
1557
  (input, options) => call(client, { "method": "post", "path": "/checks", "query": [], "hasBody": true }, {}, input, options)
1558
+ ),
1559
+ list: (
1560
+ /** List checks */
1561
+ (input, options) => list(client, { "method": "get", "path": "/checks", "query": ["limit", "cursor", "before", "subject", "refused"], "hasBody": false }, {}, input, options, true)
1298
1562
  )
1299
1563
  },
1300
1564
  limits: {
@@ -1311,9 +1575,13 @@ function resources(client) {
1311
1575
  /** Add credits to a balance */
1312
1576
  (limitId, input, options) => call(client, { "method": "post", "path": "/limits/{limitId}/credits", "query": [], "hasBody": true }, { "limitId": limitId }, input, options)
1313
1577
  ),
1578
+ get: (
1579
+ /** Get a credit */
1580
+ (limitId, creditId, options) => call(client, { "method": "get", "path": "/limits/{limitId}/credits/{creditId}", "query": [], "hasBody": false }, { "limitId": limitId, "creditId": creditId }, void 0, options)
1581
+ ),
1314
1582
  list: (
1315
1583
  /** List a balance's credits */
1316
- (limitId, input, options) => call(client, { "method": "get", "path": "/limits/{limitId}/credits", "query": ["limit", "cursor", "before", "subjectId"], "hasBody": false }, { "limitId": limitId }, input, options)
1584
+ (limitId, input, options) => list(client, { "method": "get", "path": "/limits/{limitId}/credits", "query": ["limit", "cursor", "before", "subjectId"], "hasBody": false }, { "limitId": limitId }, input, options, true)
1317
1585
  )
1318
1586
  },
1319
1587
  get: (
@@ -1322,7 +1590,7 @@ function resources(client) {
1322
1590
  ),
1323
1591
  list: (
1324
1592
  /** List limits */
1325
- (input, options) => call(client, { "method": "get", "path": "/limits", "query": ["limit", "cursor", "subjectKind", "action", "archived"], "hasBody": false }, {}, input, options)
1593
+ (input, options) => list(client, { "method": "get", "path": "/limits", "query": ["limit", "cursor", "subjectKind", "action", "archived"], "hasBody": false }, {}, input, options, true)
1326
1594
  ),
1327
1595
  restore: (
1328
1596
  /** Restore an archived limit */
@@ -1346,6 +1614,10 @@ function resources(client) {
1346
1614
  /** Extend a reservation */
1347
1615
  (reservationId, input, options) => call(client, { "method": "post", "path": "/reservations/{reservationId}/extend", "query": [], "hasBody": true }, { "reservationId": reservationId }, input, options)
1348
1616
  ),
1617
+ get: (
1618
+ /** Get a reservation */
1619
+ (reservationId, options) => call(client, { "method": "get", "path": "/reservations/{reservationId}", "query": [], "hasBody": false }, { "reservationId": reservationId }, void 0, options)
1620
+ ),
1349
1621
  release: (
1350
1622
  /** Release a reservation */
1351
1623
  (reservationId, options) => call(client, { "method": "post", "path": "/reservations/{reservationId}/release", "query": [], "hasBody": false }, { "reservationId": reservationId }, void 0, options)
@@ -1356,12 +1628,30 @@ function resources(client) {
1356
1628
  /** Get a subject */
1357
1629
  (subjectKind, subjectId, options) => call(client, { "method": "get", "path": "/subjects/{subjectKind}/{subjectId}", "query": [], "hasBody": false }, { "subjectKind": subjectKind, "subjectId": subjectId }, void 0, options)
1358
1630
  ),
1631
+ import: (
1632
+ /** Name many subjects */
1633
+ (input, options) => call(client, { "method": "post", "path": "/subjects/import", "query": [], "hasBody": true }, {}, input, options)
1634
+ ),
1635
+ list: (
1636
+ /** List subjects */
1637
+ (input, options) => list(client, { "method": "get", "path": "/subjects", "query": ["limit", "cursor", "kind", "label", "q"], "hasBody": false }, {}, input, options, true)
1638
+ ),
1639
+ names: {
1640
+ delete: (
1641
+ /** Erase a subject's name and labels */
1642
+ (subjectKind, subjectId, options) => call(client, { "method": "delete", "path": "/subjects/{subjectKind}/{subjectId}/names", "query": [], "hasBody": false }, { "subjectKind": subjectKind, "subjectId": subjectId }, void 0, options)
1643
+ )
1644
+ },
1359
1645
  reset: (
1360
1646
  /** Reset a subject's limits */
1361
1647
  (subjectKind, subjectId, input, options) => call(client, { "method": "post", "path": "/subjects/{subjectKind}/{subjectId}/reset", "query": [], "hasBody": true }, { "subjectKind": subjectKind, "subjectId": subjectId }, input, options)
1362
1648
  ),
1649
+ standing: (
1650
+ /** Get where a subject stands */
1651
+ (subjectKind, subjectId, input, options) => call(client, { "method": "get", "path": "/subjects/{subjectKind}/{subjectId}/standing", "query": ["shared"], "hasBody": false }, { "subjectKind": subjectKind, "subjectId": subjectId }, input, options)
1652
+ ),
1363
1653
  update: (
1364
- /** Set a subject's billing date */
1654
+ /** Update a subject */
1365
1655
  (subjectKind, subjectId, input, options) => call(client, { "method": "patch", "path": "/subjects/{subjectKind}/{subjectId}", "query": [], "hasBody": true }, { "subjectKind": subjectKind, "subjectId": subjectId }, input, options)
1366
1656
  )
1367
1657
  },
@@ -1374,13 +1664,9 @@ function resources(client) {
1374
1664
  /** Get a limit's usage over time */
1375
1665
  (input, options) => call(client, { "method": "get", "path": "/usage", "query": ["limitId", "limitName", "subject", "period", "from", "to", "granularity"], "hasBody": false }, {}, input, options)
1376
1666
  ),
1377
- standing: (
1378
- /** Get where a subject stands */
1379
- (input, options) => call(client, { "method": "get", "path": "/usage/standing", "query": ["subject", "shared"], "hasBody": false }, {}, input, options)
1380
- ),
1381
1667
  subjects: (
1382
1668
  /** List who is using a limit */
1383
- (input, options) => call(client, { "method": "get", "path": "/usage/subjects", "query": ["limitId", "limitName", "period", "from", "to", "sort", "limit"], "hasBody": false }, {}, input, options)
1669
+ (input, options) => call(client, { "method": "get", "path": "/usage/subjects", "query": ["limitId", "limitName", "period", "from", "to", "sort", "top"], "hasBody": false }, {}, input, options)
1384
1670
  )
1385
1671
  },
1386
1672
  user: {
@@ -1397,7 +1683,7 @@ function resources(client) {
1397
1683
  approvalActions: {
1398
1684
  list: (
1399
1685
  /** List the actions you can ask approval for */
1400
- (options) => call(client, { "method": "get", "path": "/workspace/approval-actions", "query": [], "hasBody": false }, {}, void 0, options)
1686
+ (options) => list(client, { "method": "get", "path": "/workspace/approval-actions", "query": [], "hasBody": false }, {}, void 0, options, false)
1401
1687
  )
1402
1688
  },
1403
1689
  approvalRequests: {
@@ -1407,23 +1693,23 @@ function resources(client) {
1407
1693
  ),
1408
1694
  get: (
1409
1695
  /** Check an approval request */
1410
- (requestId, options) => call(client, { "method": "get", "path": "/workspace/approval-requests/{requestId}", "query": [], "hasBody": false }, { "requestId": requestId }, void 0, options)
1696
+ (approvalRequestId, options) => call(client, { "method": "get", "path": "/workspace/approval-requests/{approvalRequestId}", "query": [], "hasBody": false }, { "approvalRequestId": approvalRequestId }, void 0, options)
1411
1697
  ),
1412
1698
  redeem: (
1413
1699
  /** Redeem an approved request */
1414
- (requestId, options) => call(client, { "method": "post", "path": "/workspace/approval-requests/{requestId}/redeem", "query": [], "hasBody": false }, { "requestId": requestId }, void 0, options)
1700
+ (approvalRequestId, options) => call(client, { "method": "post", "path": "/workspace/approval-requests/{approvalRequestId}/redeem", "query": [], "hasBody": false }, { "approvalRequestId": approvalRequestId }, void 0, options)
1415
1701
  )
1416
1702
  },
1417
1703
  auditEvents: {
1418
1704
  list: (
1419
1705
  /** List workspace audit events */
1420
- (input, options) => call(client, { "method": "get", "path": "/workspace/audit-events", "query": ["limit", "cursor", "before", "action", "actor"], "hasBody": false }, {}, input, options)
1706
+ (input, options) => list(client, { "method": "get", "path": "/workspace/audit-events", "query": ["limit", "cursor", "before", "action", "actor"], "hasBody": false }, {}, input, options, true)
1421
1707
  )
1422
1708
  },
1423
1709
  eventTypes: {
1424
1710
  list: (
1425
1711
  /** List event types */
1426
- (options) => call(client, { "method": "get", "path": "/workspace/event-types", "query": [], "hasBody": false }, {}, void 0, options)
1712
+ (options) => list(client, { "method": "get", "path": "/workspace/event-types", "query": [], "hasBody": false }, {}, void 0, options, false)
1427
1713
  )
1428
1714
  },
1429
1715
  get: (
@@ -1433,29 +1719,31 @@ function resources(client) {
1433
1719
  invitations: {
1434
1720
  list: (
1435
1721
  /** List pending invitations */
1436
- (input, options) => call(client, { "method": "get", "path": "/workspace/invitations", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options)
1722
+ (input, options) => list(client, { "method": "get", "path": "/workspace/invitations", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options, true)
1437
1723
  )
1438
1724
  },
1439
1725
  members: {
1440
1726
  list: (
1441
1727
  /** List workspace members */
1442
- (input, options) => call(client, { "method": "get", "path": "/workspace/members", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options)
1728
+ (input, options) => list(client, { "method": "get", "path": "/workspace/members", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options, true)
1729
+ )
1730
+ },
1731
+ planUsage: {
1732
+ get: (
1733
+ /** Get your plan's usage this period */
1734
+ (options) => call(client, { "method": "get", "path": "/workspace/plan-usage", "query": [], "hasBody": false }, {}, void 0, options)
1443
1735
  )
1444
1736
  },
1445
1737
  teams: {
1446
1738
  list: (
1447
1739
  /** List teams */
1448
- (input, options) => call(client, { "method": "get", "path": "/workspace/teams", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options)
1740
+ (input, options) => list(client, { "method": "get", "path": "/workspace/teams", "query": ["limit", "cursor"], "hasBody": false }, {}, input, options, true)
1449
1741
  )
1450
1742
  },
1451
- usage: (
1452
- /** Get your plan's usage this period */
1453
- (options) => call(client, { "method": "get", "path": "/workspace/usage", "query": [], "hasBody": false }, {}, void 0, options)
1454
- ),
1455
1743
  webhookDeliveries: {
1456
1744
  list: (
1457
1745
  /** List an endpoint's deliveries */
1458
- (endpointId, input, options) => call(client, { "method": "get", "path": "/workspace/webhook-endpoints/{endpointId}/deliveries", "query": ["limit", "cursor", "before", "status"], "hasBody": false }, { "endpointId": endpointId }, input, options)
1746
+ (endpointId, input, options) => list(client, { "method": "get", "path": "/workspace/webhook-endpoints/{endpointId}/deliveries", "query": ["limit", "cursor", "before", "status"], "hasBody": false }, { "endpointId": endpointId }, input, options, true)
1459
1747
  ),
1460
1748
  redeliver: (
1461
1749
  /** Redeliver an event */
@@ -1481,7 +1769,7 @@ function resources(client) {
1481
1769
  ),
1482
1770
  list: (
1483
1771
  /** List webhook endpoints */
1484
- (options) => call(client, { "method": "get", "path": "/workspace/webhook-endpoints", "query": [], "hasBody": false }, {}, void 0, options)
1772
+ (options) => list(client, { "method": "get", "path": "/workspace/webhook-endpoints", "query": [], "hasBody": false }, {}, void 0, options, false)
1485
1773
  ),
1486
1774
  test: (
1487
1775
  /** Send a test event */
@@ -1496,11 +1784,13 @@ function resources(client) {
1496
1784
  };
1497
1785
  }
1498
1786
 
1787
+ // node_modules/@limitry/sdk/dist/version.js
1788
+ var VERSION = "1.0.0-rc.18";
1789
+
1499
1790
  // node_modules/@limitry/sdk/dist/webhooks.js
1500
- var WebhookVerificationError = class extends Error {
1791
+ var WebhookVerificationError = class extends SdkError {
1501
1792
  constructor(message) {
1502
1793
  super(message);
1503
- this.name = "WebhookVerificationError";
1504
1794
  }
1505
1795
  };
1506
1796
  function header(headers, name) {
@@ -1568,7 +1858,8 @@ async function verifyWebhook(body, headers, secret, options = {}) {
1568
1858
  // node_modules/@limitry/sdk/dist/index.js
1569
1859
  var API_KEY_ENV = `${brand2.identifier.toUpperCase()}_API_KEY`;
1570
1860
  var TOKEN_ENV = `${brand2.identifier.toUpperCase()}_TOKEN`;
1571
- var DEFAULT_API = `https://api.${brand2.domain}`;
1861
+ var BASE_URL_ENV = `${brand2.identifier.toUpperCase()}_BASE_URL`;
1862
+ var DEFAULT_BASE_URL = `https://api.${brand2.domain}`;
1572
1863
  function createClient2(options = {}) {
1573
1864
  const client = createBaseClient(options);
1574
1865
  const extend = Reflect.get(product_exports, "productMethods");
@@ -1590,14 +1881,22 @@ function createBaseClient(options) {
1590
1881
  if (!token) {
1591
1882
  throw new Error(`${brand2.productName}: no API key. Pass { apiKey } or set ${API_KEY_ENV}.`);
1592
1883
  }
1593
- const origin = withoutTrailingSlashes(options.api ?? DEFAULT_API);
1594
- const send = options.fetch ?? ((request) => fetch(request));
1884
+ const origin = withoutTrailingSlashes(options.baseURL || environment()?.[BASE_URL_ENV] || DEFAULT_BASE_URL);
1885
+ const send2 = withAttemptTimeout(options.fetch ?? ((request) => fetch(request)), options.timeout ?? DEFAULT_TIMEOUT_MS);
1886
+ const sending = options.maxRetries === 0 ? withoutProductRetryHeader(send2) : withRetries(send2, { maxRetries: options.maxRetries });
1595
1887
  const client = createClient({
1596
1888
  baseUrl: `${origin}/v1`,
1597
- fetch: options.maxRetries === 0 ? withoutProductRetryHeader(send) : withRetries(send, { maxRetries: options.maxRetries })
1889
+ fetch: withConnectionErrors(sending)
1598
1890
  });
1599
1891
  client.use({
1600
1892
  onRequest({ request }) {
1893
+ for (const [name, value] of Object.entries(options.defaultHeaders ?? {})) {
1894
+ if (!request.headers.has(name))
1895
+ request.headers.set(name, value);
1896
+ }
1897
+ if (!("document" in globalThis) && !request.headers.has("user-agent")) {
1898
+ request.headers.set("user-agent", USER_AGENT);
1899
+ }
1601
1900
  request.headers.set("authorization", `Bearer ${token}`);
1602
1901
  if (options.workspace && !request.headers.has("x-workspace")) {
1603
1902
  request.headers.set("x-workspace", options.workspace);
@@ -1612,9 +1911,13 @@ function createBaseClient(options) {
1612
1911
  webhooks: { verify: verifyWebhook }
1613
1912
  });
1614
1913
  }
1615
- function credentialFromEnvironment() {
1914
+ var USER_AGENT = `${brand2.name}-node/${VERSION}`;
1915
+ function environment() {
1616
1916
  const runtime = globalThis;
1617
- const env = runtime.process?.env;
1917
+ return runtime.process?.env;
1918
+ }
1919
+ function credentialFromEnvironment() {
1920
+ const env = environment();
1618
1921
  return env?.[API_KEY_ENV] || env?.[TOKEN_ENV] || void 0;
1619
1922
  }
1620
1923
  function unwrap(result) {
@@ -1638,12 +1941,12 @@ var CommanderError = class extends Error {
1638
1941
  * @param {string} code an id string representing the error
1639
1942
  * @param {string} message human-readable description of the error
1640
1943
  */
1641
- constructor(exitCode, code2, message) {
1944
+ constructor(exitCode2, code2, message) {
1642
1945
  super(message);
1643
1946
  Error.captureStackTrace(this, this.constructor);
1644
1947
  this.name = this.constructor.name;
1645
1948
  this.code = code2;
1646
- this.exitCode = exitCode;
1949
+ this.exitCode = exitCode2;
1647
1950
  this.nestedError = void 0;
1648
1951
  }
1649
1952
  };
@@ -3199,11 +3502,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
3199
3502
  * @return never
3200
3503
  * @private
3201
3504
  */
3202
- _exit(exitCode, code2, message) {
3505
+ _exit(exitCode2, code2, message) {
3203
3506
  if (this._exitCallback) {
3204
- this._exitCallback(new CommanderError(exitCode, code2, message));
3507
+ this._exitCallback(new CommanderError(exitCode2, code2, message));
3205
3508
  }
3206
- process2.exit(exitCode);
3509
+ process2.exit(exitCode2);
3207
3510
  }
3208
3511
  /**
3209
3512
  * Register callback `fn` for the command.
@@ -4354,9 +4657,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
4354
4657
  this.outputHelp({ error: true });
4355
4658
  }
4356
4659
  const config2 = errorOptions || {};
4357
- const exitCode = config2.exitCode || 1;
4660
+ const exitCode2 = config2.exitCode || 1;
4358
4661
  const code2 = config2.code || "commander.error";
4359
- this._exit(exitCode, code2, message);
4662
+ this._exit(exitCode2, code2, message);
4360
4663
  }
4361
4664
  /**
4362
4665
  * Apply any option related environment variables, if option does
@@ -4475,10 +4778,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
4475
4778
  * @param {string} flag
4476
4779
  * @private
4477
4780
  */
4478
- unknownOption(flag2) {
4781
+ unknownOption(flag) {
4479
4782
  if (this._allowUnknownOption) return;
4480
4783
  let suggestion = "";
4481
- if (flag2.startsWith("--") && this._showSuggestionAfterError) {
4784
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
4482
4785
  let candidateFlags = [];
4483
4786
  let command = this;
4484
4787
  do {
@@ -4486,9 +4789,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
4486
4789
  candidateFlags = candidateFlags.concat(moreFlags);
4487
4790
  command = command.parent;
4488
4791
  } while (command && !command._enablePositionalOptions);
4489
- suggestion = suggestSimilar(flag2, candidateFlags);
4792
+ suggestion = suggestSimilar(flag, candidateFlags);
4490
4793
  }
4491
- const message = `error: unknown option '${flag2}'${suggestion}`;
4794
+ const message = `error: unknown option '${flag}'${suggestion}`;
4492
4795
  this.error(message, { code: "commander.unknownOption" });
4493
4796
  }
4494
4797
  /**
@@ -4898,11 +5201,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
4898
5201
  */
4899
5202
  help(contextOptions) {
4900
5203
  this.outputHelp(contextOptions);
4901
- let exitCode = Number(process2.exitCode ?? 0);
4902
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
4903
- exitCode = 1;
5204
+ let exitCode2 = Number(process2.exitCode ?? 0);
5205
+ if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
5206
+ exitCode2 = 1;
4904
5207
  }
4905
- this._exit(exitCode, "commander.help", "(outputHelp)");
5208
+ this._exit(exitCode2, "commander.help", "(outputHelp)");
4906
5209
  }
4907
5210
  /**
4908
5211
  * // Do a little typing to coordinate emit and listener for the help text events.
@@ -5048,13 +5351,13 @@ function browserLogin(options) {
5048
5351
  return;
5049
5352
  }
5050
5353
  const fields = url.searchParams;
5051
- const send = (status, title, text) => res.writeHead(status, {
5354
+ const send2 = (status, title, text) => res.writeHead(status, {
5052
5355
  "content-type": "text/html; charset=utf-8",
5053
5356
  "cache-control": "no-store",
5054
5357
  "referrer-policy": "no-referrer"
5055
5358
  }).end(PAGE(title, text));
5056
5359
  if (fields.get("state") !== state) {
5057
- send(
5360
+ send2(
5058
5361
  400,
5059
5362
  "Not this login",
5060
5363
  "This sign-in did not come from the terminal that is waiting. Run login again."
@@ -5062,16 +5365,16 @@ function browserLogin(options) {
5062
5365
  return;
5063
5366
  }
5064
5367
  if (fields.get("error")) {
5065
- send(200, "Sign-in cancelled", "You can close this tab.");
5368
+ send2(200, "Sign-in cancelled", "You can close this tab.");
5066
5369
  finish(() => reject(new Error("sign-in was denied in the browser")));
5067
5370
  return;
5068
5371
  }
5069
5372
  const token = decrypt(fields.get("token") ?? "");
5070
5373
  if (!token) {
5071
- send(400, "Something went wrong", "Run login again.");
5374
+ send2(400, "Something went wrong", "Run login again.");
5072
5375
  return;
5073
5376
  }
5074
- send(
5377
+ send2(
5075
5378
  200,
5076
5379
  "You are signed in",
5077
5380
  "Return to your terminal. You can close this tab."
@@ -5123,6 +5426,9 @@ import {
5123
5426
  writeFileSync
5124
5427
  } from "node:fs";
5125
5428
  import { join } from "node:path";
5429
+ function baseURLEnvVar() {
5430
+ return BASE_URL_ENV;
5431
+ }
5126
5432
  function environmentEnvVar() {
5127
5433
  return `${brand.identifier.toUpperCase()}_ENVIRONMENT`;
5128
5434
  }
@@ -5150,12 +5456,13 @@ function writeConfig(homeDir, config2) {
5150
5456
  }
5151
5457
  function resolveSettings(env, homeDir, flags = {}) {
5152
5458
  const config2 = readConfig(homeDir);
5153
- const environment2 = flags.environment ? { environment: flags.environment, environmentSource: "flag" } : env[environmentEnvVar()] ? { environment: env[environmentEnvVar()], environmentSource: "env" } : config2.environment ? { environment: config2.environment, environmentSource: "config" } : { environment: void 0, environmentSource: null };
5459
+ const environment3 = flags.environment ? { environment: flags.environment, environmentSource: "flag" } : env[environmentEnvVar()] ? { environment: env[environmentEnvVar()], environmentSource: "env" } : config2.environment ? { environment: config2.environment, environmentSource: "config" } : { environment: void 0, environmentSource: null };
5154
5460
  return {
5155
- ...environment2,
5156
- api: withoutTrailingSlashes2(
5157
- env[`${brand.identifier.toUpperCase()}_API`] ?? config2.api ?? DEFAULT_API
5461
+ ...environment3,
5462
+ baseURL: withoutTrailingSlashes2(
5463
+ flags.baseUrl || env[BASE_URL_ENV] || config2.baseURL || DEFAULT_BASE_URL
5158
5464
  ),
5465
+ baseURLSource: flags.baseUrl ? "flag" : env[BASE_URL_ENV] ? "env" : config2.baseURL ? "config" : null,
5159
5466
  token: env[tokenEnvVar()] ?? config2.token,
5160
5467
  workspace: env[`${brand.identifier.toUpperCase()}_WORKSPACE`] ?? config2.workspace
5161
5468
  };
@@ -5166,6 +5473,28 @@ function withoutTrailingSlashes2(url) {
5166
5473
  return url.slice(0, end);
5167
5474
  }
5168
5475
 
5476
+ // src/errors.ts
5477
+ var EXIT = {
5478
+ ok: 0,
5479
+ failure: 1,
5480
+ usage: 2,
5481
+ auth: 4
5482
+ };
5483
+ var UsageError = class extends Error {
5484
+ exitCode = EXIT.usage;
5485
+ constructor(message) {
5486
+ super(message);
5487
+ this.name = "UsageError";
5488
+ }
5489
+ };
5490
+ var NotLoggedInError = class extends Error {
5491
+ exitCode = EXIT.auth;
5492
+ constructor(message) {
5493
+ super(message);
5494
+ this.name = "NotLoggedInError";
5495
+ }
5496
+ };
5497
+
5169
5498
  // src/http.ts
5170
5499
  async function rawRequest(ctx, options) {
5171
5500
  const needsWorkspace = !options.path.startsWith("/v1/user");
@@ -5174,7 +5503,7 @@ async function rawRequest(ctx, options) {
5174
5503
  return unwrap(
5175
5504
  await client.request(options.method, options.path, {
5176
5505
  // The client's base URL ends in /v1; the path given here is absolute.
5177
- baseUrl: ctx.credentials({ workspace: workspace2 }).api,
5506
+ baseUrl: ctx.credentials({ workspace: workspace2 }).baseURL,
5178
5507
  body: options.body
5179
5508
  })
5180
5509
  );
@@ -5273,9 +5602,10 @@ var approvals = (program2, ctx) => {
5273
5602
  // src/usage.ts
5274
5603
  var usage = (program2, ctx) => {
5275
5604
  const workspace2 = program2.commands.find((c) => c.name() === "workspace") ?? program2.command("workspace");
5276
- workspace2.command("usage").description("Show your plan's usage this period").option("--workspace <slug>", "act in this workspace for one call").option("--json", "machine-readable output").action(async (options) => {
5605
+ const planUsage = workspace2.commands.find((c) => c.name() === "plan-usage") ?? workspace2.command("plan-usage").description("Your plan's usage this period");
5606
+ planUsage.command("get").description("Show your plan's usage this period").option("--workspace <slug>", "act in this workspace for one call").option("--json", "machine-readable output").action(async (options) => {
5277
5607
  const result = unwrap(
5278
- await ctx.client({ workspace: options.workspace }).GET("/workspace/usage")
5608
+ await ctx.client({ workspace: options.workspace }).GET("/workspace/plan-usage")
5279
5609
  );
5280
5610
  if (options.json) {
5281
5611
  ctx.io.stdout(json(result));
@@ -5307,13 +5637,14 @@ function usageLines(usage2) {
5307
5637
  async function me(ctx) {
5308
5638
  return unwrap(await ctx.client({ workspace: false }).GET("/user/me"));
5309
5639
  }
5310
- async function saveToken(ctx, token, api2) {
5640
+ async function saveToken(ctx, token) {
5641
+ const { baseURL, baseURLSource } = ctx.settings();
5311
5642
  if (!token.startsWith(`pat_${brand.identifier}_`)) {
5312
5643
  throw new Error(`that is not a ${brand.productName} personal access token`);
5313
5644
  }
5314
5645
  const previous = readConfig(ctx.io.homeDir);
5315
5646
  const config2 = { ...previous, token };
5316
- if (api2) config2.api = api2;
5647
+ if (baseURLSource === "flag") config2.baseURL = baseURL;
5317
5648
  writeConfig(ctx.io.homeDir, config2);
5318
5649
  let user;
5319
5650
  try {
@@ -5343,24 +5674,28 @@ async function saveToken(ctx, token, api2) {
5343
5674
  var login = (program2, ctx) => {
5344
5675
  program2.command("login").description(
5345
5676
  "Sign in through the browser, or store a personal access token with --token"
5346
- ).option("--token <pat>", "a personal access token (CI, servers)").option("--api <origin>", `API origin (default ${DEFAULT_API})`).option("--web <origin>", "web app origin for the browser sign-in").action(async (options) => {
5677
+ ).option("--token <pat>", "a personal access token (CI, servers)").option("--web <origin>", "web app origin for the browser sign-in").addHelpText(
5678
+ "after",
5679
+ `
5680
+ The global --base-url signs in to another API (default ${DEFAULT_BASE_URL}), and is saved for later commands.`
5681
+ ).action(async (options) => {
5347
5682
  if (!productFeatures.personalTokens) {
5348
5683
  throw new Error(
5349
5684
  `${brand.productName} has no personal access tokens, so this command line cannot sign in.`
5350
5685
  );
5351
5686
  }
5352
5687
  if (options.token) {
5353
- await saveToken(ctx, options.token, options.api);
5688
+ await saveToken(ctx, options.token);
5354
5689
  return;
5355
5690
  }
5356
5691
  if (!ctx.io.interactive) {
5357
5692
  ctx.io.stderr(
5358
5693
  `Paste a personal access token (Account \u2192 Personal access tokens in ${brand.productName}), then Enter:`
5359
5694
  );
5360
- await saveToken(ctx, (await ctx.io.stdin()).trim(), options.api);
5695
+ await saveToken(ctx, (await ctx.io.stdin()).trim());
5361
5696
  return;
5362
5697
  }
5363
- const api2 = options.api ?? ctx.settings().api;
5698
+ const api2 = ctx.settings().baseURL;
5364
5699
  const webOrigin = options.web ?? webOriginFor(api2);
5365
5700
  if (!webOrigin) {
5366
5701
  throw new Error(
@@ -5376,15 +5711,15 @@ var login = (program2, ctx) => {
5376
5711
  ${url}`
5377
5712
  )
5378
5713
  });
5379
- await saveToken(ctx, token, options.api);
5714
+ await saveToken(ctx, token);
5380
5715
  });
5381
5716
  };
5382
5717
  var logout = (program2, ctx) => {
5383
5718
  program2.command("logout").description("Revoke the stored token and forget it").action(async () => {
5384
5719
  const config2 = readConfig(ctx.io.homeDir);
5385
5720
  if (config2.token) {
5386
- const revoked = await ctx.io.fetch(
5387
- new Request(`${ctx.settings().api}/v1/user/token`, {
5721
+ const revoked = await ctx.fetch(
5722
+ new Request(`${ctx.settings().baseURL}/v1/user/token`, {
5388
5723
  method: "DELETE",
5389
5724
  headers: { authorization: `Bearer ${config2.token}` }
5390
5725
  })
@@ -5442,7 +5777,7 @@ var workspace = (program2, ctx) => {
5442
5777
  ctx.io.stdout(`Default workspace: ${slug}`);
5443
5778
  });
5444
5779
  };
5445
- var environment = (program2, ctx) => {
5780
+ var environment2 = (program2, ctx) => {
5446
5781
  const group = program2.command("environment").description("Choose the environment commands act in");
5447
5782
  group.command("list", { isDefault: true }).description("Show the environment commands act in").action(() => {
5448
5783
  const { environment: current, environmentSource } = ctx.settings();
@@ -5485,9 +5820,16 @@ var api = (program2, ctx) => {
5485
5820
  program2.command("api <method> <path>").description("Call any API endpoint directly, in the selected workspace").option("--data <json>", "JSON request body").option("--workspace <slug>", "act in this workspace for one call").action(
5486
5821
  async (method, path2, options) => {
5487
5822
  if (!path2.startsWith("/")) {
5488
- throw new Error("usage: api <method> </v1/...> [--data '<json>']");
5823
+ throw new UsageError(
5824
+ "usage: api <method> </v1/...> [--data '<json>']"
5825
+ );
5826
+ }
5827
+ let body;
5828
+ try {
5829
+ body = options.data === void 0 ? void 0 : JSON.parse(options.data);
5830
+ } catch {
5831
+ throw new UsageError("--data must be JSON");
5489
5832
  }
5490
- const body = options.data === void 0 ? void 0 : JSON.parse(options.data);
5491
5833
  ctx.io.stdout(
5492
5834
  json(
5493
5835
  await rawRequest(ctx, {
@@ -5506,8 +5848,8 @@ var config = (program2, ctx) => {
5506
5848
  const settings = ctx.settings();
5507
5849
  ctx.io.stdout(
5508
5850
  json({
5509
- api: settings.api,
5510
- apiDefault: DEFAULT_API,
5851
+ baseURL: settings.baseURL,
5852
+ baseURLDefault: DEFAULT_BASE_URL,
5511
5853
  token: settings.token ? `${settings.token.slice(0, 12)}\u2026` : null,
5512
5854
  tokenSource: ctx.io.env[tokenEnvVar()] ? tokenEnvVar() : settings.token ? "config" : null,
5513
5855
  workspace: settings.workspace ?? null,
@@ -5523,7 +5865,7 @@ var platformCommands = [
5523
5865
  logout,
5524
5866
  whoami,
5525
5867
  workspace,
5526
- environment,
5868
+ environment2,
5527
5869
  api,
5528
5870
  config,
5529
5871
  approvals,
@@ -5591,10 +5933,10 @@ var OPERATIONS = [
5591
5933
  "in": "body",
5592
5934
  "type": "json",
5593
5935
  "required": true,
5594
- "description": 'Who is acting, such as `{"kind": "user", "id": "usr_123"}`.',
5936
+ "description": 'Who is acting, such as `{"kind": "user", "id": "user_123"}`.',
5595
5937
  "example": {
5596
5938
  "kind": "user",
5597
- "id": "usr_123"
5939
+ "id": "user_123"
5598
5940
  },
5599
5941
  "schema": {
5600
5942
  "type": "object",
@@ -5616,7 +5958,7 @@ var OPERATIONS = [
5616
5958
  "kind",
5617
5959
  "id"
5618
5960
  ],
5619
- "description": 'Who is acting, such as `{"kind": "user", "id": "usr_123"}`.'
5961
+ "description": 'Who is acting, such as `{"kind": "user", "id": "user_123"}`.'
5620
5962
  }
5621
5963
  },
5622
5964
  {
@@ -5714,48 +6056,144 @@ var OPERATIONS = [
5714
6056
  "scope": "checks:write"
5715
6057
  },
5716
6058
  {
5717
- "operationId": "limits.archive",
5718
- "method": "post",
5719
- "path": "/limits/{limitId}/archive",
5720
- "summary": "Archive a limit",
6059
+ "operationId": "checks.list",
6060
+ "method": "get",
6061
+ "path": "/checks",
6062
+ "summary": "List checks",
5721
6063
  "cli": {
5722
- "command": "limits archive",
5723
- "args": [
5724
- "limitId"
5725
- ],
6064
+ "command": "checks list",
6065
+ "args": [],
5726
6066
  "confirm": false
5727
6067
  },
5728
6068
  "mcp": {
5729
6069
  "exposed": true,
5730
- "name": "limits_archive",
6070
+ "name": "checks_list",
5731
6071
  "hints": {
5732
- "readOnlyHint": false,
6072
+ "readOnlyHint": true,
5733
6073
  "destructiveHint": false,
5734
- "idempotentHint": false
6074
+ "idempotentHint": true
5735
6075
  }
5736
6076
  },
5737
- "description": "Archives a limit, so checks stop enforcing it at once and it leaves the list. Archiving erases nothing. Limitry keeps the limit's usage history and credits, and `POST /v1/limits/{limitId}/restore` brings it back. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6077
+ "description": "Lists the checks of the last 3 days, newest first, with every subject each one named and whether Limitry allowed it. A refused check says whose budget refused it. Name a `subject` as `kind:id` for only the checks that named it, or set `refused` for only refused ones. Send `before` to start from a moment. Limitry keeps the last 3 days, and at most 100,000 checks in each environment. Results come a page at a time.",
5738
6078
  "fields": [
5739
6079
  {
5740
- "name": "limitId",
5741
- "in": "path",
6080
+ "name": "limit",
6081
+ "in": "query",
6082
+ "type": "number",
6083
+ "required": false,
6084
+ "description": "Items per page, 1\u2013100 (default 25).",
6085
+ "example": 25,
6086
+ "schema": {
6087
+ "type": "integer",
6088
+ "minimum": 1,
6089
+ "maximum": 100,
6090
+ "default": 25,
6091
+ "description": "Items per page, 1\u2013100 (default 25)."
6092
+ }
6093
+ },
6094
+ {
6095
+ "name": "cursor",
6096
+ "in": "query",
5742
6097
  "type": "string",
5743
- "required": true,
5744
- "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case.",
5745
- "example": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
6098
+ "required": false,
6099
+ "description": "Opaque token from a previous page's nextCursor.",
5746
6100
  "schema": {
5747
6101
  "type": "string",
5748
- "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case."
6102
+ "description": "Opaque token from a previous page's nextCursor."
6103
+ }
6104
+ },
6105
+ {
6106
+ "name": "before",
6107
+ "in": "query",
6108
+ "type": "string",
6109
+ "required": false,
6110
+ "description": "Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on.",
6111
+ "example": "2026-11-01T00:00:00.000Z",
6112
+ "schema": {
6113
+ "type": "string",
6114
+ "format": "date-time",
6115
+ "description": "Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on."
6116
+ }
6117
+ },
6118
+ {
6119
+ "name": "subject",
6120
+ "in": "query",
6121
+ "type": "string",
6122
+ "required": false,
6123
+ "description": "Only checks that named this subject, as `kind:id`.",
6124
+ "example": "user:user_123",
6125
+ "schema": {
6126
+ "type": "string",
6127
+ "maxLength": 301,
6128
+ "description": "Only checks that named this subject, as `kind:id`."
6129
+ }
6130
+ },
6131
+ {
6132
+ "name": "refused",
6133
+ "in": "query",
6134
+ "type": "string",
6135
+ "required": false,
6136
+ "description": "`true` for only refused checks.",
6137
+ "example": "true",
6138
+ "schema": {
6139
+ "type": "string",
6140
+ "enum": [
6141
+ "true",
6142
+ "false"
6143
+ ],
6144
+ "description": "`true` for only refused checks."
5749
6145
  }
5750
6146
  }
5751
6147
  ],
5752
6148
  "hasBody": false,
6149
+ "paginated": true,
5753
6150
  "workspace": true,
5754
6151
  "acceptsApiKey": true,
5755
- "scope": "limits:write"
6152
+ "scope": "limits:read"
5756
6153
  },
5757
6154
  {
5758
- "operationId": "limits.create",
6155
+ "operationId": "limits.archive",
6156
+ "method": "post",
6157
+ "path": "/limits/{limitId}/archive",
6158
+ "summary": "Archive a limit",
6159
+ "cli": {
6160
+ "command": "limits archive",
6161
+ "args": [
6162
+ "limitId"
6163
+ ],
6164
+ "confirm": false
6165
+ },
6166
+ "mcp": {
6167
+ "exposed": true,
6168
+ "name": "limits_archive",
6169
+ "hints": {
6170
+ "readOnlyHint": false,
6171
+ "destructiveHint": false,
6172
+ "idempotentHint": false
6173
+ }
6174
+ },
6175
+ "description": "Archives a limit, so checks stop enforcing it at once and it leaves the list. Archiving erases nothing. Limitry keeps the limit's usage history and credits, and `POST /v1/limits/{limitId}/restore` brings it back. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6176
+ "fields": [
6177
+ {
6178
+ "name": "limitId",
6179
+ "in": "path",
6180
+ "type": "string",
6181
+ "required": true,
6182
+ "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case.",
6183
+ "example": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
6184
+ "schema": {
6185
+ "type": "string",
6186
+ "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case."
6187
+ }
6188
+ }
6189
+ ],
6190
+ "hasBody": false,
6191
+ "workspace": true,
6192
+ "acceptsApiKey": true,
6193
+ "scope": "limits:write"
6194
+ },
6195
+ {
6196
+ "operationId": "limits.create",
5759
6197
  "method": "post",
5760
6198
  "path": "/limits",
5761
6199
  "summary": "Create a limit",
@@ -5794,7 +6232,7 @@ var OPERATIONS = [
5794
6232
  "in": "body",
5795
6233
  "type": "json",
5796
6234
  "required": true,
5797
- "description": 'Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "usr_123"}` covers one.',
6235
+ "description": 'Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "user_123"}` covers one.',
5798
6236
  "example": {
5799
6237
  "kind": "user"
5800
6238
  },
@@ -5820,7 +6258,7 @@ var OPERATIONS = [
5820
6258
  "required": [
5821
6259
  "kind"
5822
6260
  ],
5823
- "description": 'Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "usr_123"}` covers one.'
6261
+ "description": 'Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "user_123"}` covers one.'
5824
6262
  }
5825
6263
  },
5826
6264
  {
@@ -6053,6 +6491,60 @@ var OPERATIONS = [
6053
6491
  "acceptsApiKey": true,
6054
6492
  "scope": "limits:write"
6055
6493
  },
6494
+ {
6495
+ "operationId": "limits.credits.get",
6496
+ "method": "get",
6497
+ "path": "/limits/{limitId}/credits/{creditId}",
6498
+ "summary": "Get a credit",
6499
+ "cli": {
6500
+ "command": "limits credits get",
6501
+ "args": [
6502
+ "limitId",
6503
+ "creditId"
6504
+ ],
6505
+ "confirm": false
6506
+ },
6507
+ "mcp": {
6508
+ "exposed": true,
6509
+ "name": "limits_credits_get",
6510
+ "hints": {
6511
+ "readOnlyHint": true,
6512
+ "destructiveHint": false,
6513
+ "idempotentHint": true
6514
+ }
6515
+ },
6516
+ "description": "Returns one credit added to a subject's balance on this limit.",
6517
+ "fields": [
6518
+ {
6519
+ "name": "limitId",
6520
+ "in": "path",
6521
+ "type": "string",
6522
+ "required": true,
6523
+ "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case.",
6524
+ "example": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
6525
+ "schema": {
6526
+ "type": "string",
6527
+ "description": "The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case."
6528
+ }
6529
+ },
6530
+ {
6531
+ "name": "creditId",
6532
+ "in": "path",
6533
+ "type": "string",
6534
+ "required": true,
6535
+ "description": "The credit's ID.",
6536
+ "example": "crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73",
6537
+ "schema": {
6538
+ "type": "string",
6539
+ "description": "The credit's ID."
6540
+ }
6541
+ }
6542
+ ],
6543
+ "hasBody": false,
6544
+ "workspace": true,
6545
+ "acceptsApiKey": true,
6546
+ "scope": "limits:read"
6547
+ },
6056
6548
  {
6057
6549
  "operationId": "limits.credits.list",
6058
6550
  "method": "get",
@@ -6143,6 +6635,7 @@ var OPERATIONS = [
6143
6635
  }
6144
6636
  ],
6145
6637
  "hasBody": false,
6638
+ "paginated": true,
6146
6639
  "workspace": true,
6147
6640
  "acceptsApiKey": true,
6148
6641
  "scope": "limits:read"
@@ -6278,6 +6771,7 @@ var OPERATIONS = [
6278
6771
  }
6279
6772
  ],
6280
6773
  "hasBody": false,
6774
+ "paginated": true,
6281
6775
  "workspace": true,
6282
6776
  "acceptsApiKey": true,
6283
6777
  "scope": "limits:read"
@@ -6343,7 +6837,7 @@ var OPERATIONS = [
6343
6837
  "idempotentHint": false
6344
6838
  }
6345
6839
  },
6346
- "description": "Makes the environment's limits match the list in `limits`, pairing them up by name. It creates the limits that are missing and changes the ones that differ, where an omitted field means its default. With `archiveMissing`, it also archives the active limits the list doesn't name. Running it twice changes nothing the second time. Limitry checks the whole list before writing anything. If any entry has a problem, nothing changes, and the 400 lists each problem in `details`. Otherwise Limitry writes every change at once. You can't change a limit's subject, action, unit, window, every, start or rolling under the same name, so rename the entry to do that. With `preview`, it returns what it would do without writing anything. This is the call behind `limitry sync`, for keeping your limits in a file in your repository. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6840
+ "description": "Makes the environment's limits match the list in `limits`, pairing them up by name. It creates the limits that are missing and changes the ones that differ, where an omitted field means its default. With `archiveMissing`, it also archives the active limits the list doesn't name. Running it twice changes nothing the second time. Limitry checks the whole list before writing anything. If any entry has a problem, nothing changes, and the 400 lists each problem in `details`. Otherwise Limitry writes every change at once. You can't change a limit's subject, action, unit, window, every, start or rolling under the same name, so rename the entry to do that. With `dryRun`, it returns what it would do without writing anything. What a sync sets is locked in the app until the next sync, which names its `source`. This is the call behind `limitry sync`, for keeping your limits in a file in your repository. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6347
6841
  "fields": [
6348
6842
  {
6349
6843
  "name": "limits",
@@ -6403,7 +6897,7 @@ var OPERATIONS = [
6403
6897
  }
6404
6898
  },
6405
6899
  {
6406
- "name": "preview",
6900
+ "name": "dryRun",
6407
6901
  "in": "body",
6408
6902
  "type": "boolean",
6409
6903
  "required": false,
@@ -6412,6 +6906,64 @@ var OPERATIONS = [
6412
6906
  "type": "boolean",
6413
6907
  "description": "Whether to report what the sync would do without changing anything. Default: false."
6414
6908
  }
6909
+ },
6910
+ {
6911
+ "name": "source",
6912
+ "in": "body",
6913
+ "type": "string",
6914
+ "required": false,
6915
+ "description": "Where these limits come from, such as the file's name or your deploy's. The app and the 409 name it on every limit the sync sets, as in \"Set by limitry.json\". The CLI sends the file's name. Default: `a sync`.",
6916
+ "example": "limitry.json",
6917
+ "schema": {
6918
+ "type": "string",
6919
+ "minLength": 1,
6920
+ "maxLength": 100,
6921
+ "description": "Where these limits come from, such as the file's name or your deploy's. The app and the 409 name it on every limit the sync sets, as in \"Set by limitry.json\". The CLI sends the file's name. Default: `a sync`."
6922
+ }
6923
+ },
6924
+ {
6925
+ "name": "kinds",
6926
+ "in": "body",
6927
+ "type": "json",
6928
+ "required": false,
6929
+ "description": "The workspace's kinds, from the top level down: how the app names each and the order its subject pages use for Above and Below. They replace the workspace's kinds, for test and live alike, so only owners and admins (or a workspace key) can send them. Leave this out to leave the kinds alone. Labels only: checks and the API keep using the kinds themselves.",
6930
+ "schema": {
6931
+ "type": "array",
6932
+ "items": {
6933
+ "type": "object",
6934
+ "properties": {
6935
+ "kind": {
6936
+ "type": "string",
6937
+ "minLength": 1,
6938
+ "maxLength": 100,
6939
+ "description": "The kind, as your checks send it."
6940
+ },
6941
+ "displayName": {
6942
+ "type": [
6943
+ "string",
6944
+ "null"
6945
+ ],
6946
+ "minLength": 1,
6947
+ "maxLength": 60,
6948
+ "description": "How the app names it. Default: the kind, starting with a capital letter."
6949
+ },
6950
+ "plural": {
6951
+ "type": [
6952
+ "string",
6953
+ "null"
6954
+ ],
6955
+ "minLength": 1,
6956
+ "maxLength": 60,
6957
+ "description": "Its plural in the app. Default: one made from the name."
6958
+ }
6959
+ },
6960
+ "required": [
6961
+ "kind"
6962
+ ]
6963
+ },
6964
+ "maxItems": 100,
6965
+ "description": "The workspace's kinds, from the top level down: how the app names each and the order its subject pages use for Above and Below. They replace the workspace's kinds, for test and live alike, so only owners and admins (or a workspace key) can send them. Leave this out to leave the kinds alone. Labels only: checks and the API keep using the kinds themselves."
6966
+ }
6415
6967
  }
6416
6968
  ],
6417
6969
  "hasBody": true,
@@ -6440,7 +6992,7 @@ var OPERATIONS = [
6440
6992
  "idempotentHint": false
6441
6993
  }
6442
6994
  },
6443
- "description": "Changes a limit's name, amount, fail mode or whether it's enabled. Checks use the new rule at once. You can't change a limit's subject, action, unit, window, every, start or rolling, and a request that tries gets a 400. To count something different, create a new limit and archive this one. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6995
+ "description": "Changes a limit's name, amount, fail mode or whether it's enabled. Checks use the new rule at once. You can't change a limit's subject, action, unit, window, every, start or rolling, and a request that tries gets a 400. To count something different, create a new limit and archive this one. A limit a sync sets (its `setIn`) changes only through the sync. A request to change one gets a 409 that names where the sync came from, unless it sends `override` with a reason. An override lasts until the next sync. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6444
6996
  "fields": [
6445
6997
  {
6446
6998
  "name": "limitId",
@@ -6625,6 +7177,31 @@ var OPERATIONS = [
6625
7177
  "type": "boolean",
6626
7178
  "description": "Whether the limit counts the last windows up to each check. You set it when you create the limit. To change it later, create a new limit and archive this one."
6627
7179
  }
7180
+ },
7181
+ {
7182
+ "name": "override",
7183
+ "in": "body",
7184
+ "type": "json",
7185
+ "required": false,
7186
+ "description": "Changes a limit a sync sets, until the next sync puts its values back. Only owners and admins, or a workspace API key, can override. Without it, changing such a limit gets a 409. You can't rename it, because the sync finds it by name.",
7187
+ "example": {
7188
+ "reason": "Support incident: raised for a customer"
7189
+ },
7190
+ "schema": {
7191
+ "type": "object",
7192
+ "properties": {
7193
+ "reason": {
7194
+ "type": "string",
7195
+ "minLength": 1,
7196
+ "maxLength": 500,
7197
+ "description": "Why, for the audit log and the limit's page."
7198
+ }
7199
+ },
7200
+ "required": [
7201
+ "reason"
7202
+ ],
7203
+ "description": "Changes a limit a sync sets, until the next sync puts its values back. Only owners and admins, or a workspace API key, can override. Without it, changing such a limit gets a 409. You can't rename it, because the sync finds it by name."
7204
+ }
6628
7205
  }
6629
7206
  ],
6630
7207
  "hasBody": true,
@@ -6653,7 +7230,7 @@ var OPERATIONS = [
6653
7230
  "idempotentHint": false
6654
7231
  }
6655
7232
  },
6656
- "description": "Commits a reservation with the amount actually used (`cost`). If `cost` is less than the amount reserved, the rest goes back at once. If it's more, Limitry charges the whole `cost`, since the work happened. A commit up to 24 hours after the reservation expired still charges `cost`. Repeating a commit with the same `cost` returns the same result, and a different `cost` gets a 400. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.",
7233
+ "description": "Commits a reservation with the amount actually used (`cost`). If `cost` is less than the amount reserved, the rest goes back at once. If it's more, Limitry charges the whole `cost`, since the work happened. A commit up to 24 hours after the reservation expired still charges `cost`. Repeating a commit with the same `cost` returns the same result, and a different `cost` gets a 400. Committing a released reservation gets a 409. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.",
6657
7234
  "fields": [
6658
7235
  {
6659
7236
  "name": "reservationId",
@@ -6739,6 +7316,46 @@ var OPERATIONS = [
6739
7316
  "acceptsApiKey": true,
6740
7317
  "scope": "checks:write"
6741
7318
  },
7319
+ {
7320
+ "operationId": "reservations.get",
7321
+ "method": "get",
7322
+ "path": "/reservations/{reservationId}",
7323
+ "summary": "Get a reservation",
7324
+ "cli": {
7325
+ "command": "reservations get",
7326
+ "args": [
7327
+ "reservationId"
7328
+ ],
7329
+ "confirm": false
7330
+ },
7331
+ "mcp": {
7332
+ "exposed": true,
7333
+ "name": "reservations_get",
7334
+ "hints": {
7335
+ "readOnlyHint": true,
7336
+ "destructiveHint": false,
7337
+ "idempotentHint": true
7338
+ }
7339
+ },
7340
+ "description": "Returns a reservation as it stands: held, committed, released or expired, with what it reserved and what it finally used. A reservation past its expiry that nobody committed or released reads as expired. Reading it changes nothing.",
7341
+ "fields": [
7342
+ {
7343
+ "name": "reservationId",
7344
+ "in": "path",
7345
+ "type": "string",
7346
+ "required": true,
7347
+ "description": "The reservation's ID.",
7348
+ "schema": {
7349
+ "type": "string",
7350
+ "description": "The reservation's ID."
7351
+ }
7352
+ }
7353
+ ],
7354
+ "hasBody": false,
7355
+ "workspace": true,
7356
+ "acceptsApiKey": true,
7357
+ "scope": "checks:write"
7358
+ },
6742
7359
  {
6743
7360
  "operationId": "reservations.release",
6744
7361
  "method": "post",
@@ -6798,10 +7415,309 @@ var OPERATIONS = [
6798
7415
  "hints": {
6799
7416
  "readOnlyHint": true,
6800
7417
  "destructiveHint": false,
6801
- "idempotentHint": true
7418
+ "idempotentHint": true
7419
+ }
7420
+ },
7421
+ "description": "Returns a subject: its billing date, the day its `billing_date` limits start each new period, its name and labels if you gave it any, its budgets, and the subjects it's checked with. A subject is one of yours, such as a user, a team or an agent. It exists once a check names it. Its links say what was spent within each budget this period: within another subject's budget, or another subject within its own.",
7422
+ "fields": [
7423
+ {
7424
+ "name": "subjectKind",
7425
+ "in": "path",
7426
+ "type": "string",
7427
+ "required": true,
7428
+ "description": "The subject kind's ID.",
7429
+ "example": "team",
7430
+ "schema": {
7431
+ "type": "string",
7432
+ "minLength": 1,
7433
+ "maxLength": 100,
7434
+ "description": "The subject kind's ID."
7435
+ }
7436
+ },
7437
+ {
7438
+ "name": "subjectId",
7439
+ "in": "path",
7440
+ "type": "string",
7441
+ "required": true,
7442
+ "description": "The subject's ID.",
7443
+ "example": "team_42",
7444
+ "schema": {
7445
+ "type": "string",
7446
+ "minLength": 1,
7447
+ "maxLength": 200,
7448
+ "description": "The subject's ID."
7449
+ }
7450
+ }
7451
+ ],
7452
+ "hasBody": false,
7453
+ "workspace": true,
7454
+ "acceptsApiKey": true,
7455
+ "scope": "limits:read"
7456
+ },
7457
+ {
7458
+ "operationId": "subjects.import",
7459
+ "method": "post",
7460
+ "path": "/subjects/import",
7461
+ "summary": "Name many subjects",
7462
+ "cli": {
7463
+ "command": "subjects import",
7464
+ "args": [],
7465
+ "confirm": false
7466
+ },
7467
+ "mcp": {
7468
+ "exposed": true,
7469
+ "name": "subjects_import",
7470
+ "hints": {
7471
+ "readOnlyHint": false,
7472
+ "destructiveHint": false,
7473
+ "idempotentHint": false
7474
+ }
7475
+ },
7476
+ "description": "Sets the name and labels of up to 1,000 subjects at once, such as when you first connect your user list. Each item works like updating that subject's name and labels: a field you leave out stays as it is, and null clears it. Limitry checks every item before it saves any, so a bad item saves nothing. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
7477
+ "fields": [
7478
+ {
7479
+ "name": "items",
7480
+ "in": "body",
7481
+ "type": "json",
7482
+ "required": true,
7483
+ "description": "The subjects to name, from 1 to 1,000: each its kind and ID, and its name, its labels or both.",
7484
+ "example": [
7485
+ {
7486
+ "kind": "team",
7487
+ "id": "team_42",
7488
+ "name": "Design team",
7489
+ "labels": {
7490
+ "plan": "pro"
7491
+ }
7492
+ }
7493
+ ],
7494
+ "schema": {
7495
+ "type": "array",
7496
+ "items": {
7497
+ "type": "object",
7498
+ "properties": {
7499
+ "kind": {
7500
+ "type": "string",
7501
+ "minLength": 1,
7502
+ "maxLength": 100
7503
+ },
7504
+ "id": {
7505
+ "type": "string",
7506
+ "minLength": 1,
7507
+ "maxLength": 200
7508
+ },
7509
+ "name": {
7510
+ "type": [
7511
+ "string",
7512
+ "null"
7513
+ ],
7514
+ "minLength": 1,
7515
+ "maxLength": 200,
7516
+ "description": "A name people can read, up to 200 characters. Optional. Names don't have to be unique. Send null to clear it."
7517
+ },
7518
+ "labels": {
7519
+ "type": [
7520
+ "object",
7521
+ "null"
7522
+ ],
7523
+ "additionalProperties": {
7524
+ "type": "string",
7525
+ "maxLength": 200
7526
+ },
7527
+ "description": "Labels to filter by, such as a plan or a region: up to 20 keys of up to 40 characters, with values of up to 200. Optional. They replace the subject's labels. Send null to clear them."
7528
+ }
7529
+ },
7530
+ "required": [
7531
+ "kind",
7532
+ "id"
7533
+ ]
7534
+ },
7535
+ "minItems": 1,
7536
+ "maxItems": 1e3,
7537
+ "description": "The subjects to name, from 1 to 1,000: each its kind and ID, and its name, its labels or both."
7538
+ }
7539
+ }
7540
+ ],
7541
+ "hasBody": true,
7542
+ "workspace": true,
7543
+ "acceptsApiKey": true,
7544
+ "scope": "limits:write"
7545
+ },
7546
+ {
7547
+ "operationId": "subjects.list",
7548
+ "method": "get",
7549
+ "path": "/subjects",
7550
+ "summary": "List subjects",
7551
+ "cli": {
7552
+ "command": "subjects list",
7553
+ "args": [],
7554
+ "confirm": false
7555
+ },
7556
+ "mcp": {
7557
+ "exposed": true,
7558
+ "name": "subjects_list",
7559
+ "hints": {
7560
+ "readOnlyHint": true,
7561
+ "destructiveHint": false,
7562
+ "idempotentHint": true
7563
+ }
7564
+ },
7565
+ "description": "Lists every subject your checks have named in this environment, and every one you named, most recently checked first. Filter by `kind` or by one `label`, and search the name or the ID with `q`. Results come a page at a time.",
7566
+ "fields": [
7567
+ {
7568
+ "name": "limit",
7569
+ "in": "query",
7570
+ "type": "number",
7571
+ "required": false,
7572
+ "description": "Items per page, 1\u2013100 (default 25).",
7573
+ "example": 25,
7574
+ "schema": {
7575
+ "type": "integer",
7576
+ "minimum": 1,
7577
+ "maximum": 100,
7578
+ "default": 25,
7579
+ "description": "Items per page, 1\u2013100 (default 25)."
7580
+ }
7581
+ },
7582
+ {
7583
+ "name": "cursor",
7584
+ "in": "query",
7585
+ "type": "string",
7586
+ "required": false,
7587
+ "description": "Opaque token from a previous page's nextCursor.",
7588
+ "schema": {
7589
+ "type": "string",
7590
+ "description": "Opaque token from a previous page's nextCursor."
7591
+ }
7592
+ },
7593
+ {
7594
+ "name": "kind",
7595
+ "in": "query",
7596
+ "type": "string",
7597
+ "required": false,
7598
+ "description": "Only subjects of this kind.",
7599
+ "example": "team",
7600
+ "schema": {
7601
+ "type": "string",
7602
+ "minLength": 1,
7603
+ "maxLength": 100,
7604
+ "description": "Only subjects of this kind."
7605
+ }
7606
+ },
7607
+ {
7608
+ "name": "label",
7609
+ "in": "query",
7610
+ "type": "string",
7611
+ "required": false,
7612
+ "description": "Only subjects with this label, as `key:value`.",
7613
+ "example": "plan:pro",
7614
+ "schema": {
7615
+ "type": "string",
7616
+ "maxLength": 250,
7617
+ "description": "Only subjects with this label, as `key:value`."
7618
+ }
7619
+ },
7620
+ {
7621
+ "name": "q",
7622
+ "in": "query",
7623
+ "type": "string",
7624
+ "required": false,
7625
+ "description": "Only subjects whose name or ID contains this text, in any case.",
7626
+ "example": "design",
7627
+ "schema": {
7628
+ "type": "string",
7629
+ "maxLength": 200,
7630
+ "description": "Only subjects whose name or ID contains this text, in any case."
7631
+ }
7632
+ }
7633
+ ],
7634
+ "hasBody": false,
7635
+ "paginated": true,
7636
+ "workspace": true,
7637
+ "acceptsApiKey": true,
7638
+ "scope": "limits:read"
7639
+ },
7640
+ {
7641
+ "operationId": "subjects.names.delete",
7642
+ "method": "delete",
7643
+ "path": "/subjects/{subjectKind}/{subjectId}/names",
7644
+ "summary": "Erase a subject's name and labels",
7645
+ "cli": {
7646
+ "command": "subjects names delete",
7647
+ "args": [
7648
+ "subjectKind",
7649
+ "subjectId"
7650
+ ],
7651
+ "confirm": true
7652
+ },
7653
+ "mcp": {
7654
+ "exposed": true,
7655
+ "name": "subjects_names_delete",
7656
+ "hints": {
7657
+ "readOnlyHint": false,
7658
+ "destructiveHint": true,
7659
+ "idempotentHint": true
7660
+ }
7661
+ },
7662
+ "description": "Erases the name and labels you gave a subject. Its limits, usage and billing date stay, because they're kept by its ID. Use it when one of your users asks you to delete their data. Erasing a subject with no name or labels succeeds too. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
7663
+ "fields": [
7664
+ {
7665
+ "name": "subjectKind",
7666
+ "in": "path",
7667
+ "type": "string",
7668
+ "required": true,
7669
+ "description": "The subject kind's ID.",
7670
+ "example": "team",
7671
+ "schema": {
7672
+ "type": "string",
7673
+ "minLength": 1,
7674
+ "maxLength": 100,
7675
+ "description": "The subject kind's ID."
7676
+ }
7677
+ },
7678
+ {
7679
+ "name": "subjectId",
7680
+ "in": "path",
7681
+ "type": "string",
7682
+ "required": true,
7683
+ "description": "The subject's ID.",
7684
+ "example": "team_42",
7685
+ "schema": {
7686
+ "type": "string",
7687
+ "minLength": 1,
7688
+ "maxLength": 200,
7689
+ "description": "The subject's ID."
7690
+ }
7691
+ }
7692
+ ],
7693
+ "hasBody": false,
7694
+ "workspace": true,
7695
+ "acceptsApiKey": true,
7696
+ "scope": "limits:write"
7697
+ },
7698
+ {
7699
+ "operationId": "subjects.reset",
7700
+ "method": "post",
7701
+ "path": "/subjects/{subjectKind}/{subjectId}/reset",
7702
+ "summary": "Reset a subject's limits",
7703
+ "cli": {
7704
+ "command": "subjects reset",
7705
+ "args": [
7706
+ "subjectKind",
7707
+ "subjectId"
7708
+ ],
7709
+ "confirm": false
7710
+ },
7711
+ "mcp": {
7712
+ "exposed": true,
7713
+ "name": "subjects_reset",
7714
+ "hints": {
7715
+ "readOnlyHint": false,
7716
+ "destructiveHint": false,
7717
+ "idempotentHint": false
6802
7718
  }
6803
7719
  },
6804
- "description": "Returns a subject's billing date, the day its `billing_date` limits start each new period. A subject is one of yours, such as a user, a team or an agent. It exists once a check names it.",
7720
+ "description": "Resets one limit on a subject now, or every limit on it. Send `limitId` for one limit, or `{}` for all of them. Use it for goodwill, a promotion or support. The schedule doesn't move, so the next reset still happens when it normally would. A balance goes back to its amount, and the reset skips concurrent limits. With an Idempotency-Key, a repeated request resets only once. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6805
7721
  "fields": [
6806
7722
  {
6807
7723
  "name": "subjectKind",
@@ -6830,20 +7746,32 @@ var OPERATIONS = [
6830
7746
  "maxLength": 200,
6831
7747
  "description": "The subject's ID."
6832
7748
  }
7749
+ },
7750
+ {
7751
+ "name": "limitId",
7752
+ "in": "body",
7753
+ "type": "string",
7754
+ "required": false,
7755
+ "description": "The one limit to reset. Default: every limit on the subject.",
7756
+ "example": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
7757
+ "schema": {
7758
+ "type": "string",
7759
+ "description": "The one limit to reset. Default: every limit on the subject."
7760
+ }
6833
7761
  }
6834
7762
  ],
6835
- "hasBody": false,
7763
+ "hasBody": true,
6836
7764
  "workspace": true,
6837
7765
  "acceptsApiKey": true,
6838
- "scope": "limits:read"
7766
+ "scope": "limits:write"
6839
7767
  },
6840
7768
  {
6841
- "operationId": "subjects.reset",
6842
- "method": "post",
6843
- "path": "/subjects/{subjectKind}/{subjectId}/reset",
6844
- "summary": "Reset a subject's limits",
7769
+ "operationId": "subjects.standing",
7770
+ "method": "get",
7771
+ "path": "/subjects/{subjectKind}/{subjectId}/standing",
7772
+ "summary": "Get where a subject stands",
6845
7773
  "cli": {
6846
- "command": "subjects reset",
7774
+ "command": "subjects standing",
6847
7775
  "args": [
6848
7776
  "subjectKind",
6849
7777
  "subjectId"
@@ -6852,14 +7780,14 @@ var OPERATIONS = [
6852
7780
  },
6853
7781
  "mcp": {
6854
7782
  "exposed": true,
6855
- "name": "subjects_reset",
7783
+ "name": "subjects_standing",
6856
7784
  "hints": {
6857
- "readOnlyHint": false,
7785
+ "readOnlyHint": true,
6858
7786
  "destructiveHint": false,
6859
- "idempotentHint": false
7787
+ "idempotentHint": true
6860
7788
  }
6861
7789
  },
6862
- "description": "Resets one limit on a subject now, or every limit on it. Send `limitId` for one limit, or `{}` for all of them. Use it for goodwill, a promotion or support. The schedule doesn't move, so the next reset still happens when it normally would. A balance goes back to its amount, and the reset skips concurrent limits. With an Idempotency-Key, a repeated request resets only once. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
7790
+ "description": "Returns where one subject stands on every enabled limit, exact as of now. It covers the subject's own limits and the limits on its shared subjects. List the shared subjects in `shared`, such as `team:team_42`. Each limit shows what's used, what's left and when it resets. Use it to show your users where they stand. Call it from your server with your key, never from a browser. It isn't a check, so it counts nothing. A subject with no limits returns an empty `limits` list.",
6863
7791
  "fields": [
6864
7792
  {
6865
7793
  "name": "subjectKind",
@@ -6890,28 +7818,29 @@ var OPERATIONS = [
6890
7818
  }
6891
7819
  },
6892
7820
  {
6893
- "name": "limitId",
6894
- "in": "body",
7821
+ "name": "shared",
7822
+ "in": "query",
6895
7823
  "type": "string",
6896
7824
  "required": false,
6897
- "description": "The one limit to reset. Default: every limit on the subject.",
6898
- "example": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
7825
+ "description": "Shared subjects to include, as comma-separated `kind:id` pairs. Send up to 4.",
7826
+ "example": "team:team_42",
6899
7827
  "schema": {
6900
7828
  "type": "string",
6901
- "description": "The one limit to reset. Default: every limit on the subject."
7829
+ "maxLength": 1500,
7830
+ "description": "Shared subjects to include, as comma-separated `kind:id` pairs. Send up to 4."
6902
7831
  }
6903
7832
  }
6904
7833
  ],
6905
- "hasBody": true,
7834
+ "hasBody": false,
6906
7835
  "workspace": true,
6907
7836
  "acceptsApiKey": true,
6908
- "scope": "limits:write"
7837
+ "scope": "limits:read"
6909
7838
  },
6910
7839
  {
6911
7840
  "operationId": "subjects.update",
6912
7841
  "method": "patch",
6913
7842
  "path": "/subjects/{subjectKind}/{subjectId}",
6914
- "summary": "Set a subject's billing date",
7843
+ "summary": "Update a subject",
6915
7844
  "cli": {
6916
7845
  "command": "subjects update",
6917
7846
  "args": [
@@ -6929,7 +7858,7 @@ var OPERATIONS = [
6929
7858
  "idempotentHint": false
6930
7859
  }
6931
7860
  },
6932
- "description": "Sets the date a subject's `billing_date` limits count their periods from. Usually this is the subscription's start date, set from your billing system's webhook. The subject's allowance then resets on its own billing day, and a monthly limit still resets monthly on an annual plan. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
7861
+ "description": "Sets a subject's billing date, its name, its labels, or any of them. A field you leave out stays as it is, and null clears a name or labels. Labels you send replace the subject's labels. The billing date is the moment the subject's `billing_date` limits count their periods from, usually the subscription's start, set from your billing system's webhook. The subject's allowance then resets on its own billing day, and a monthly limit still resets monthly on an annual plan. A name and labels are optional, and checks never need them. With a personal access token, only owners and admins can call this. A workspace API key with this scope can.",
6933
7862
  "fields": [
6934
7863
  {
6935
7864
  "name": "subjectKind",
@@ -6960,16 +7889,54 @@ var OPERATIONS = [
6960
7889
  }
6961
7890
  },
6962
7891
  {
6963
- "name": "billingDate",
7892
+ "name": "billingAnchorAt",
6964
7893
  "in": "body",
6965
7894
  "type": "string",
6966
- "required": true,
6967
- "description": "The date and time the subject's periods start from, in ISO 8601, such as a subscription's start.",
7895
+ "required": false,
7896
+ "description": "The moment the subject's periods start from, in ISO 8601, such as a subscription's start.",
6968
7897
  "example": "2026-03-17T14:30:00Z",
6969
7898
  "schema": {
6970
7899
  "type": "string",
6971
7900
  "format": "date-time",
6972
- "description": "The date and time the subject's periods start from, in ISO 8601, such as a subscription's start."
7901
+ "description": "The moment the subject's periods start from, in ISO 8601, such as a subscription's start."
7902
+ }
7903
+ },
7904
+ {
7905
+ "name": "name",
7906
+ "in": "body",
7907
+ "type": "string",
7908
+ "required": false,
7909
+ "description": "A name people can read, up to 200 characters. Optional. Names don't have to be unique. Send null to clear it.",
7910
+ "example": "Design team",
7911
+ "schema": {
7912
+ "type": [
7913
+ "string",
7914
+ "null"
7915
+ ],
7916
+ "minLength": 1,
7917
+ "maxLength": 200,
7918
+ "description": "A name people can read, up to 200 characters. Optional. Names don't have to be unique. Send null to clear it."
7919
+ }
7920
+ },
7921
+ {
7922
+ "name": "labels",
7923
+ "in": "body",
7924
+ "type": "json",
7925
+ "required": false,
7926
+ "description": "Labels to filter by, such as a plan or a region: up to 20 keys of up to 40 characters, with values of up to 200. Optional. They replace the subject's labels. Send null to clear them.",
7927
+ "example": {
7928
+ "plan": "pro"
7929
+ },
7930
+ "schema": {
7931
+ "type": [
7932
+ "object",
7933
+ "null"
7934
+ ],
7935
+ "additionalProperties": {
7936
+ "type": "string",
7937
+ "maxLength": 200
7938
+ },
7939
+ "description": "Labels to filter by, such as a plan or a region: up to 20 keys of up to 40 characters, with values of up to 200. Optional. They replace the subject's labels. Send null to clear them."
6973
7940
  }
6974
7941
  }
6975
7942
  ],
@@ -7135,7 +8102,7 @@ var OPERATIONS = [
7135
8102
  "type": "string",
7136
8103
  "required": false,
7137
8104
  "description": "One subject, as `kind:id`, to see its usage instead of every subject's.",
7138
- "example": "user:usr_123",
8105
+ "example": "user:user_123",
7139
8106
  "schema": {
7140
8107
  "type": "string",
7141
8108
  "minLength": 3,
@@ -7210,59 +8177,6 @@ var OPERATIONS = [
7210
8177
  "acceptsApiKey": true,
7211
8178
  "scope": "limits:read"
7212
8179
  },
7213
- {
7214
- "operationId": "usage.standing",
7215
- "method": "get",
7216
- "path": "/usage/standing",
7217
- "summary": "Get where a subject stands",
7218
- "cli": {
7219
- "command": "usage standing",
7220
- "args": [],
7221
- "confirm": false
7222
- },
7223
- "mcp": {
7224
- "exposed": true,
7225
- "name": "usage_standing",
7226
- "hints": {
7227
- "readOnlyHint": true,
7228
- "destructiveHint": false,
7229
- "idempotentHint": true
7230
- }
7231
- },
7232
- "description": "Returns where one subject stands on every enabled limit, exact as of now. It covers the subject's own limits and the limits on its shared subjects. Name the subject as `kind:id`, such as `user:usr_123`, and list its shared subjects in `shared`, such as `team:team_42`. Each limit shows what's used, what's left and when it resets. Use it to show your users where they stand. Call it from your server with your key, never from a browser. It isn't a check, so it counts nothing. A subject with no limits returns an empty `limits` list.",
7233
- "fields": [
7234
- {
7235
- "name": "subject",
7236
- "in": "query",
7237
- "type": "string",
7238
- "required": true,
7239
- "description": "The subject, written as `kind:id` exactly as your checks send it.",
7240
- "example": "user:usr_123",
7241
- "schema": {
7242
- "type": "string",
7243
- "minLength": 3,
7244
- "maxLength": 301,
7245
- "description": "The subject, written as `kind:id` exactly as your checks send it."
7246
- }
7247
- },
7248
- {
7249
- "name": "shared",
7250
- "in": "query",
7251
- "type": "string",
7252
- "required": false,
7253
- "description": "Shared subjects to include, as comma-separated `kind:id` pairs. Send up to 4.",
7254
- "example": "team:team_42",
7255
- "schema": {
7256
- "type": "string",
7257
- "description": "Shared subjects to include, as comma-separated `kind:id` pairs. Send up to 4."
7258
- }
7259
- }
7260
- ],
7261
- "hasBody": false,
7262
- "workspace": true,
7263
- "acceptsApiKey": true,
7264
- "scope": "limits:read"
7265
- },
7266
8180
  {
7267
8181
  "operationId": "usage.subjects",
7268
8182
  "method": "get",
@@ -7371,17 +8285,17 @@ var OPERATIONS = [
7371
8285
  }
7372
8286
  },
7373
8287
  {
7374
- "name": "limit",
8288
+ "name": "top",
7375
8289
  "in": "query",
7376
8290
  "type": "number",
7377
8291
  "required": false,
7378
- "description": "How many subjects to list. Default: 50. The response holds at most 50, or 25 for a `concurrent` limit, even if you ask for more.",
8292
+ "description": "How many subjects to rank, up to 50. Default: 50. A `concurrent` limit ranks at most 25.",
7379
8293
  "schema": {
7380
8294
  "type": "integer",
7381
8295
  "minimum": 1,
7382
- "maximum": 200,
8296
+ "maximum": 50,
7383
8297
  "default": 50,
7384
- "description": "How many subjects to list. Default: 50. The response holds at most 50, or 25 for a `concurrent` limit, even if you ask for more."
8298
+ "description": "How many subjects to rank, up to 50. Default: 50. A `concurrent` limit ranks at most 25."
7385
8299
  }
7386
8300
  }
7387
8301
  ],
@@ -7449,9 +8363,10 @@ var OPERATIONS = [
7449
8363
  "idempotentHint": true
7450
8364
  }
7451
8365
  },
7452
- "description": "Lists the actions a credential can't take itself but can ask a person to approve. Each action comes with its input as a JSON Schema, who can approve it and whether it creates a secret.",
8366
+ "description": "Lists the actions a credential can't take itself but can ask a person to approve. Each action comes with its input as a JSON Schema (`inputSchema`), who can approve it and whether it creates a secret. Every action fits on one page, so `nextCursor` is null.",
7453
8367
  "fields": [],
7454
8368
  "hasBody": false,
8369
+ "paginated": true,
7455
8370
  "workspace": true,
7456
8371
  "acceptsApiKey": true,
7457
8372
  "scope": "workspace.approvals:read"
@@ -7530,12 +8445,12 @@ var OPERATIONS = [
7530
8445
  {
7531
8446
  "operationId": "workspace.approvalRequests.get",
7532
8447
  "method": "get",
7533
- "path": "/workspace/approval-requests/{requestId}",
8448
+ "path": "/workspace/approval-requests/{approvalRequestId}",
7534
8449
  "summary": "Check an approval request",
7535
8450
  "cli": {
7536
8451
  "command": "workspace approval-requests get",
7537
8452
  "args": [
7538
- "requestId"
8453
+ "approvalRequestId"
7539
8454
  ],
7540
8455
  "confirm": false
7541
8456
  },
@@ -7551,15 +8466,15 @@ var OPERATIONS = [
7551
8466
  "description": "Returns an approval request you created, with its status. A `pending` request is waiting for a person to decide. A `completed` request's action ran, and `result` holds the outcome. An `approved` request is waiting for the CLI to redeem it. A request can also be `denied`, `failed` or `expired`.",
7552
8467
  "fields": [
7553
8468
  {
7554
- "name": "requestId",
8469
+ "name": "approvalRequestId",
7555
8470
  "in": "path",
7556
8471
  "type": "string",
7557
8472
  "required": true,
7558
- "description": "The request's id.",
7559
- "example": "apr_7c2e\u2026",
8473
+ "description": "The approval request's id.",
8474
+ "example": "apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
7560
8475
  "schema": {
7561
8476
  "type": "string",
7562
- "description": "The request's id."
8477
+ "description": "The approval request's id."
7563
8478
  }
7564
8479
  }
7565
8480
  ],
@@ -7571,12 +8486,12 @@ var OPERATIONS = [
7571
8486
  {
7572
8487
  "operationId": "workspace.approvalRequests.redeem",
7573
8488
  "method": "post",
7574
- "path": "/workspace/approval-requests/{requestId}/redeem",
8489
+ "path": "/workspace/approval-requests/{approvalRequestId}/redeem",
7575
8490
  "summary": "Redeem an approved request",
7576
8491
  "cli": {
7577
8492
  "command": "workspace approval-requests redeem",
7578
8493
  "args": [
7579
- "requestId"
8494
+ "approvalRequestId"
7580
8495
  ],
7581
8496
  "confirm": false
7582
8497
  },
@@ -7587,15 +8502,15 @@ var OPERATIONS = [
7587
8502
  "description": "Runs an approved action that creates a secret, and returns the secret. The action runs only once. Only the personal access token that asked can redeem it. The CLI writes the secret to a file without printing it.",
7588
8503
  "fields": [
7589
8504
  {
7590
- "name": "requestId",
8505
+ "name": "approvalRequestId",
7591
8506
  "in": "path",
7592
8507
  "type": "string",
7593
8508
  "required": true,
7594
- "description": "The request's id.",
7595
- "example": "apr_7c2e\u2026",
8509
+ "description": "The approval request's id.",
8510
+ "example": "apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
7596
8511
  "schema": {
7597
8512
  "type": "string",
7598
- "description": "The request's id."
8513
+ "description": "The approval request's id."
7599
8514
  }
7600
8515
  }
7601
8516
  ],
@@ -7623,7 +8538,7 @@ var OPERATIONS = [
7623
8538
  "idempotentHint": true
7624
8539
  }
7625
8540
  },
7626
- "description": "Lists the workspace's audit events, newest first. Paginate with the opaque `nextCursor` token. `limit` takes 1 to 100 and defaults to 25. `before` starts from a moment. `action` keeps one kind of event, and `actor` what one person, key or token did. With a personal access token, only workspace owners can call this, as with the audit page in the app. A workspace API key always can, because it acts as the workspace itself.",
8541
+ "description": "Lists the workspace's audit events, newest first. Paginate with the opaque `nextCursor` token. `limit` takes 1 to 100 and defaults to 25. `before` starts from a moment. `action` keeps one kind of event, and `actor` what one person, key or token did. With a personal access token, only workspace owners and admins can call this, as with the audit page in the app. A workspace API key always can, because it acts as the workspace itself.",
7627
8542
  "fields": [
7628
8543
  {
7629
8544
  "name": "limit",
@@ -7670,7 +8585,7 @@ var OPERATIONS = [
7670
8585
  "type": "string",
7671
8586
  "required": false,
7672
8587
  "description": "Only events of this action.",
7673
- "example": "workspace.member_invited",
8588
+ "example": "workspace.member.invited",
7674
8589
  "schema": {
7675
8590
  "type": "string",
7676
8591
  "maxLength": 100,
@@ -7683,7 +8598,7 @@ var OPERATIONS = [
7683
8598
  "type": "string",
7684
8599
  "required": false,
7685
8600
  "description": "Only what one person did (`user:` and the item's `actor.id`), or one key or token (`credential:` and the item's `credential.id`).",
7686
- "example": "user:usr_k3TAiF2ZP5sQ",
8601
+ "example": "user:usr_4f8a2c1e-7b3d-4e9f-a6c5-2d1b0e9f8a7c",
7687
8602
  "schema": {
7688
8603
  "type": "string",
7689
8604
  "pattern": "^(user|credential):[\\w-]+$",
@@ -7692,6 +8607,7 @@ var OPERATIONS = [
7692
8607
  }
7693
8608
  ],
7694
8609
  "hasBody": false,
8610
+ "paginated": true,
7695
8611
  "workspace": true,
7696
8612
  "acceptsApiKey": true,
7697
8613
  "scope": "workspace.audit:read"
@@ -7715,9 +8631,10 @@ var OPERATIONS = [
7715
8631
  "idempotentHint": true
7716
8632
  }
7717
8633
  },
7718
- "description": "Lists every workspace event a webhook endpoint can subscribe to, and what each one means. Pass some as `eventTypes` when you add an endpoint. An endpoint without a list receives every event.",
8634
+ "description": "Lists every workspace event a webhook endpoint can subscribe to, and what each one means. Pass some as `eventTypes` when you add an endpoint. An endpoint without a list receives every event. Every type fits on one page, so `nextCursor` is null.",
7719
8635
  "fields": [],
7720
8636
  "hasBody": false,
8637
+ "paginated": true,
7721
8638
  "workspace": true,
7722
8639
  "acceptsApiKey": true,
7723
8640
  "scope": "workspace.webhooks:read"
@@ -7797,6 +8714,7 @@ var OPERATIONS = [
7797
8714
  }
7798
8715
  ],
7799
8716
  "hasBody": false,
8717
+ "paginated": true,
7800
8718
  "workspace": true,
7801
8719
  "acceptsApiKey": true,
7802
8720
  "scope": "workspace.members:read"
@@ -7850,10 +8768,37 @@ var OPERATIONS = [
7850
8768
  }
7851
8769
  ],
7852
8770
  "hasBody": false,
8771
+ "paginated": true,
7853
8772
  "workspace": true,
7854
8773
  "acceptsApiKey": true,
7855
8774
  "scope": "workspace.members:read"
7856
8775
  },
8776
+ {
8777
+ "operationId": "workspace.planUsage.get",
8778
+ "method": "get",
8779
+ "path": "/workspace/plan-usage",
8780
+ "summary": "Get your plan's usage this period",
8781
+ "cli": {
8782
+ "command": "workspace plan-usage get",
8783
+ "args": [],
8784
+ "confirm": false
8785
+ },
8786
+ "mcp": {
8787
+ "exposed": true,
8788
+ "name": "workspace_plan_usage_get",
8789
+ "hints": {
8790
+ "readOnlyHint": true,
8791
+ "destructiveHint": false,
8792
+ "idempotentHint": true
8793
+ }
8794
+ },
8795
+ "description": "Returns what the workspace used this period, with one entry for each thing its plan counts. Each entry has the plan's limit, or null when there is no limit. Each entry also says where it stands and where we start refusing new use. A period is one month from the workspace's billing date. That date comes from its subscription or, without one, from the day you created the workspace. On an annual plan, the counts still reset every month from the subscription's start.",
8796
+ "fields": [],
8797
+ "hasBody": false,
8798
+ "workspace": true,
8799
+ "acceptsApiKey": true,
8800
+ "scope": "workspace:read"
8801
+ },
7857
8802
  {
7858
8803
  "operationId": "workspace.teams.list",
7859
8804
  "method": "get",
@@ -7903,36 +8848,11 @@ var OPERATIONS = [
7903
8848
  }
7904
8849
  ],
7905
8850
  "hasBody": false,
8851
+ "paginated": true,
7906
8852
  "workspace": true,
7907
8853
  "acceptsApiKey": true,
7908
8854
  "scope": "workspace.teams:read"
7909
8855
  },
7910
- {
7911
- "operationId": "workspace.usage",
7912
- "method": "get",
7913
- "path": "/workspace/usage",
7914
- "summary": "Get your plan's usage this period",
7915
- "cli": {
7916
- "command": "workspace usage",
7917
- "args": [],
7918
- "confirm": false
7919
- },
7920
- "mcp": {
7921
- "exposed": true,
7922
- "name": "workspace_usage",
7923
- "hints": {
7924
- "readOnlyHint": true,
7925
- "destructiveHint": false,
7926
- "idempotentHint": true
7927
- }
7928
- },
7929
- "description": "Returns what the workspace used this period, with one entry for each thing its plan counts. Each entry has the plan's limit, or null when there is no limit. Each entry also says where it stands and where we start refusing new use. A period is one month from the workspace's billing date. That date comes from its subscription or, without one, from the day you created the workspace. On an annual plan, the counts still reset every month from the subscription's start.",
7930
- "fields": [],
7931
- "hasBody": false,
7932
- "workspace": true,
7933
- "acceptsApiKey": true,
7934
- "scope": "workspace:read"
7935
- },
7936
8856
  {
7937
8857
  "operationId": "workspace.webhookDeliveries.list",
7938
8858
  "method": "get",
@@ -7954,7 +8874,7 @@ var OPERATIONS = [
7954
8874
  "idempotentHint": true
7955
8875
  }
7956
8876
  },
7957
- "description": "Lists one endpoint's delivery history, newest first. Each entry shows the event's status, attempts and last HTTP status. Payloads aren't included. We keep the history for 30 days. Paginate with the opaque `nextCursor`. `before` starts from a moment, and `status` keeps one kind of delivery. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
8877
+ "description": "Lists one endpoint's delivery history, newest first. Each entry shows the delivery's state, its attempts and the last HTTP status code. Payloads aren't included. We keep the history for 30 days. Paginate with the opaque `nextCursor`. `before` starts from a moment, and `status` keeps one kind of delivery. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
7958
8878
  "fields": [
7959
8879
  {
7960
8880
  "name": "endpointId",
@@ -7962,7 +8882,7 @@ var OPERATIONS = [
7962
8882
  "type": "string",
7963
8883
  "required": true,
7964
8884
  "description": "The endpoint's ID.",
7965
- "example": "we_3f0c\u2026",
8885
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
7966
8886
  "schema": {
7967
8887
  "type": "string",
7968
8888
  "description": "The endpoint's ID."
@@ -8026,6 +8946,7 @@ var OPERATIONS = [
8026
8946
  }
8027
8947
  ],
8028
8948
  "hasBody": false,
8949
+ "paginated": true,
8029
8950
  "workspace": true,
8030
8951
  "acceptsApiKey": true,
8031
8952
  "scope": "workspace.webhooks:read"
@@ -8052,7 +8973,7 @@ var OPERATIONS = [
8052
8973
  "idempotentHint": false
8053
8974
  }
8054
8975
  },
8055
- "description": "Sends a recorded delivery's event again, as a new delivery. The new delivery gets its own history entry. The event id stays the same, so receivers can deduplicate. Redelivery only works on an enabled endpoint. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
8976
+ "description": "Sends a recorded delivery's event again, as a new delivery. The new delivery gets its own history entry. The event id stays the same, so receivers can deduplicate. Redelivery only works on an enabled endpoint. It answers 200 when we attempted the delivery right away, with the endpoint's answer, and 202 when it went to the queue. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8056
8977
  "fields": [
8057
8978
  {
8058
8979
  "name": "endpointId",
@@ -8060,7 +8981,7 @@ var OPERATIONS = [
8060
8981
  "type": "string",
8061
8982
  "required": true,
8062
8983
  "description": "The endpoint's ID.",
8063
- "example": "we_3f0c\u2026",
8984
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8064
8985
  "schema": {
8065
8986
  "type": "string",
8066
8987
  "description": "The endpoint's ID."
@@ -8072,7 +8993,7 @@ var OPERATIONS = [
8072
8993
  "type": "string",
8073
8994
  "required": true,
8074
8995
  "description": "The delivery's ID.",
8075
- "example": "del_8a1b\u2026",
8996
+ "example": "del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d",
8076
8997
  "schema": {
8077
8998
  "type": "string",
8078
8999
  "description": "The delivery's ID."
@@ -8098,7 +9019,7 @@ var OPERATIONS = [
8098
9019
  "exposed": false,
8099
9020
  "reason": "Changes where workspace data is sent. A person configures webhook endpoints (Settings \u2192 Developers in the app)."
8100
9021
  },
8101
- "description": "Registers an HTTPS URL to receive the workspace's events. Deliveries use the same signature format as Svix. The response includes the endpoint's signing secret (`whsec_\u2026`). You see it only once, so store it to verify deliveries. The API refuses private hosts and hosts without HTTPS. A workspace can have at most 10 endpoints. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9022
+ "description": "Registers an HTTPS URL to receive the workspace's events. Deliveries use the same signature format as Svix. The response is the new endpoint with its signing secret (`whsec_\u2026`) in `secret`. You see it only once, so store it to verify deliveries. The API refuses private hosts and hosts without HTTPS. A workspace can have at most 10 endpoints. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8102
9023
  "fields": [
8103
9024
  {
8104
9025
  "name": "url",
@@ -8166,7 +9087,7 @@ var OPERATIONS = [
8166
9087
  "exposed": false,
8167
9088
  "reason": "Changes where workspace data is sent. A person configures webhook endpoints (Settings \u2192 Developers in the app)."
8168
9089
  },
8169
- "description": "Deletes the endpoint and its signing secret. All deliveries to the endpoint stop. Its delivery history goes with it. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9090
+ "description": "Deletes the endpoint and its signing secret. All deliveries to the endpoint stop. Its delivery history goes with it. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8170
9091
  "fields": [
8171
9092
  {
8172
9093
  "name": "endpointId",
@@ -8174,7 +9095,7 @@ var OPERATIONS = [
8174
9095
  "type": "string",
8175
9096
  "required": true,
8176
9097
  "description": "The endpoint's ID.",
8177
- "example": "we_3f0c\u2026",
9098
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8178
9099
  "schema": {
8179
9100
  "type": "string",
8180
9101
  "description": "The endpoint's ID."
@@ -8202,7 +9123,7 @@ var OPERATIONS = [
8202
9123
  "exposed": false,
8203
9124
  "reason": "Changes where workspace data is sent. A person configures webhook endpoints (Settings \u2192 Developers in the app)."
8204
9125
  },
8205
- "description": "Resumes deliveries to an endpoint that stopped after repeated failures. The endpoint keeps its signing secret. Its failure count resets. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9126
+ "description": "Resumes deliveries to an endpoint that stopped after repeated failures. The endpoint keeps its signing secret. Its failure count resets. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8206
9127
  "fields": [
8207
9128
  {
8208
9129
  "name": "endpointId",
@@ -8210,7 +9131,7 @@ var OPERATIONS = [
8210
9131
  "type": "string",
8211
9132
  "required": true,
8212
9133
  "description": "The endpoint's ID.",
8213
- "example": "we_3f0c\u2026",
9134
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8214
9135
  "schema": {
8215
9136
  "type": "string",
8216
9137
  "description": "The endpoint's ID."
@@ -8243,7 +9164,7 @@ var OPERATIONS = [
8243
9164
  "idempotentHint": true
8244
9165
  }
8245
9166
  },
8246
- "description": "Returns one endpoint without its signing secret. It shows whether the endpoint is on, its consecutive failures and its last delivery status. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9167
+ "description": "Returns one endpoint without its signing secret. It shows whether the endpoint is on, its consecutive failures and its last delivery status. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8247
9168
  "fields": [
8248
9169
  {
8249
9170
  "name": "endpointId",
@@ -8251,7 +9172,7 @@ var OPERATIONS = [
8251
9172
  "type": "string",
8252
9173
  "required": true,
8253
9174
  "description": "The endpoint's ID.",
8254
- "example": "we_3f0c\u2026",
9175
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8255
9176
  "schema": {
8256
9177
  "type": "string",
8257
9178
  "description": "The endpoint's ID."
@@ -8282,9 +9203,10 @@ var OPERATIONS = [
8282
9203
  "idempotentHint": true
8283
9204
  }
8284
9205
  },
8285
- "description": "Lists the workspace's outgoing webhook endpoints, newest first. The list leaves out their signing secrets. A workspace has at most 10 endpoints, so the list is a single page. Its `nextCursor` is null. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9206
+ "description": "Lists the workspace's outgoing webhook endpoints, newest first. The list leaves out their signing secrets. A workspace has at most 10 endpoints, so the list is a single page. Its `nextCursor` is null. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8286
9207
  "fields": [],
8287
9208
  "hasBody": false,
9209
+ "paginated": true,
8288
9210
  "workspace": true,
8289
9211
  "acceptsApiKey": true,
8290
9212
  "scope": "workspace.webhooks:read"
@@ -8310,7 +9232,7 @@ var OPERATIONS = [
8310
9232
  "idempotentHint": false
8311
9233
  }
8312
9234
  },
8313
- "description": "Sends a `ping` event to the endpoint, signed like every delivery. Use it to check that an integration verifies and accepts deliveries. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9235
+ "description": "Sends a `ping` event to the endpoint, signed like every delivery. Use it to check that an integration verifies and accepts deliveries. It answers 200 when we attempted the delivery right away, with the endpoint's answer, and 202 when it went to the queue. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8314
9236
  "fields": [
8315
9237
  {
8316
9238
  "name": "endpointId",
@@ -8318,7 +9240,7 @@ var OPERATIONS = [
8318
9240
  "type": "string",
8319
9241
  "required": true,
8320
9242
  "description": "The endpoint's ID.",
8321
- "example": "we_3f0c\u2026",
9243
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8322
9244
  "schema": {
8323
9245
  "type": "string",
8324
9246
  "description": "The endpoint's ID."
@@ -8346,7 +9268,7 @@ var OPERATIONS = [
8346
9268
  "exposed": false,
8347
9269
  "reason": "Changes where workspace data is sent. A person configures webhook endpoints (Settings \u2192 Developers in the app)."
8348
9270
  },
8349
- "description": "Changes an endpoint's URL, description or event types in place. Only the fields you send change. The endpoint keeps its signing secret, so receivers keep verifying deliveries. A new URL must pass the same checks as on create. It must use HTTPS and can't be a private host. With a personal access token, only the workspace owner can call this. So can an admin in a Developer seat. A workspace API key with this scope can.",
9271
+ "description": "Changes an endpoint's URL, description or event types in place. Only the fields you send change. The endpoint keeps its signing secret, so receivers keep verifying deliveries. A new URL must pass the same checks as on create. It must use HTTPS and can't be a private host. With a personal access token, the workspace's owners and admins can call this, and members on the test side. A workspace API key with this scope can.",
8350
9272
  "fields": [
8351
9273
  {
8352
9274
  "name": "endpointId",
@@ -8354,7 +9276,7 @@ var OPERATIONS = [
8354
9276
  "type": "string",
8355
9277
  "required": true,
8356
9278
  "description": "The endpoint's ID.",
8357
- "example": "we_3f0c\u2026",
9279
+ "example": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
8358
9280
  "schema": {
8359
9281
  "type": "string",
8360
9282
  "description": "The endpoint's ID."
@@ -8434,6 +9356,56 @@ function coveredOperations(program2) {
8434
9356
  return covered;
8435
9357
  }
8436
9358
 
9359
+ // src/flags.ts
9360
+ function kebab(name) {
9361
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
9362
+ }
9363
+ function optionKey(flagName) {
9364
+ return flagName.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
9365
+ }
9366
+ function singular(word) {
9367
+ if (/[^aeiou]ies$/.test(word)) return `${word.slice(0, -3)}y`;
9368
+ if (/(ss|us|is)$/.test(word)) return word;
9369
+ if (/(x|ch|sh|ss)es$/.test(word)) return word.slice(0, -2);
9370
+ if (word.endsWith("s")) return word.slice(0, -1);
9371
+ return word;
9372
+ }
9373
+ function types(schema) {
9374
+ if (!schema) return [];
9375
+ const own = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
9376
+ const variants = [...schema.anyOf ?? [], ...schema.oneOf ?? []];
9377
+ return [
9378
+ ...own,
9379
+ ...variants.flatMap(types),
9380
+ ...schema.nullable ? ["null"] : []
9381
+ ];
9382
+ }
9383
+ function nullable(field) {
9384
+ return types(field.schema).includes("null");
9385
+ }
9386
+ function fieldFlag(field, taken = /* @__PURE__ */ new Set()) {
9387
+ const schema = field.schema;
9388
+ const name = kebab(field.name);
9389
+ const clear = field.in === "body" && nullable(field) ? name : void 0;
9390
+ const base = { ...clear ? { clear } : {} };
9391
+ if (field.type === "boolean") return { name, kind: "boolean", ...base };
9392
+ const all = types(schema);
9393
+ const items = schema.items ?? [...schema.anyOf ?? []].find((s) => s.items)?.items;
9394
+ const itemTypes = types(items);
9395
+ const scalar = itemTypes.length > 0 && itemTypes.every((t) => ["string", "number", "integer"].includes(t));
9396
+ if (all.includes("array") && (scalar || Array.isArray(items?.enum))) {
9397
+ const words = name.split("-");
9398
+ const one = [...words.slice(0, -1), singular(words.at(-1))].join("-");
9399
+ return {
9400
+ name: one !== name && taken.has(one) ? name : one,
9401
+ kind: "list",
9402
+ ...itemTypes.every((t) => t === "number" || t === "integer") ? { numbers: true } : {},
9403
+ ...base
9404
+ };
9405
+ }
9406
+ return { name, kind: field.type === "json" ? "json" : "value", ...base };
9407
+ }
9408
+
8437
9409
  // src/generated.ts
8438
9410
  var generatedCommands = (program2, ctx) => {
8439
9411
  const groups = /* @__PURE__ */ new Set();
@@ -8449,12 +9421,10 @@ var generatedCommands = (program2, ctx) => {
8449
9421
  }
8450
9422
  };
8451
9423
  var RESERVED = /* @__PURE__ */ new Set(["json", "yes", "workspace", "data", "environment"]);
8452
- function flag(name) {
8453
- return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
8454
- }
8455
- function optionKey(name) {
8456
- return flag(name).replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
8457
- }
9424
+ var collect = (value, previous) => [
9425
+ ...previous ?? [],
9426
+ ...value.split(",").map((part) => part.trim()).filter(Boolean)
9427
+ ];
8458
9428
  function register(program2, ctx, op, groups, hidden) {
8459
9429
  const words = op.cli.command.split(" ");
8460
9430
  const action = words.pop();
@@ -8473,22 +9443,41 @@ function register(program2, ctx, op, groups, hidden) {
8473
9443
  return;
8474
9444
  }
8475
9445
  const positional = new Set(op.cli.args);
8476
- const flags = op.fields.filter(
9446
+ const fields = op.fields.filter(
8477
9447
  (field) => !positional.has(field.name) && !RESERVED.has(field.name)
8478
9448
  );
9449
+ const names = new Set(fields.map((field) => kebab(field.name)));
9450
+ const flags = fields.map((field) => ({
9451
+ field,
9452
+ spec: fieldFlag(field, names)
9453
+ }));
8479
9454
  const command = parent.command(action, { hidden }).description(op.summary).addHelpText("after", `
8480
9455
  ${op.description}`);
8481
9456
  markOperation(command, op.operationId);
8482
- for (const arg of op.cli.args) command.argument(`<${flag(arg)}>`);
8483
- for (const field of flags) {
9457
+ for (const arg of op.cli.args) command.argument(`<${kebab(arg)}>`);
9458
+ for (const { field, spec } of flags) {
8484
9459
  const description = [
8485
9460
  field.description ?? `${field.in} field`,
9461
+ spec.kind === "list" ? "Repeat it for each value." : "",
8486
9462
  field.required ? "(required)" : ""
8487
9463
  ].filter(Boolean).join(" ");
8488
- command.option(
8489
- field.type === "boolean" ? `--${flag(field.name)}` : `--${flag(field.name)} <${field.type === "json" ? "json" : "value"}>`,
8490
- description
8491
- );
9464
+ if (spec.kind === "boolean") {
9465
+ command.option(`--${spec.name}`, description);
9466
+ command.option(`--no-${spec.name}`, `turn --${spec.name} off`);
9467
+ } else if (spec.kind === "list") {
9468
+ command.option(`--${spec.name} <value>`, description, collect);
9469
+ } else {
9470
+ command.option(
9471
+ `--${spec.name} <${spec.kind === "json" ? "json" : "value"}>`,
9472
+ description
9473
+ );
9474
+ }
9475
+ if (spec.clear) {
9476
+ command.option(`--clear-${spec.clear}`, `set ${field.name} to null`);
9477
+ }
9478
+ }
9479
+ if (op.paginated) {
9480
+ command.option("--all", "every page, not just the first");
8492
9481
  }
8493
9482
  if (op.hasBody) command.option("--data <json>", "the whole JSON body");
8494
9483
  if (op.rawBody) command.requiredOption("--file <path>", "the file to send");
@@ -8505,7 +9494,7 @@ ${op.description}`);
8505
9494
  const values = input.slice(0, op.cli.args.length);
8506
9495
  const options = input[op.cli.args.length];
8507
9496
  if (op.cli.confirm && !options.yes) {
8508
- throw new Error(
9497
+ throw new UsageError(
8509
9498
  `${op.summary} cannot be undone. Run it again with --yes to confirm.`
8510
9499
  );
8511
9500
  }
@@ -8523,62 +9512,111 @@ ${op.description}`);
8523
9512
  print(ctx, result, options.json === true);
8524
9513
  });
8525
9514
  }
8526
- function coerce(field, raw) {
8527
- if (field.type === "number") {
8528
- const n = Number(raw);
8529
- if (Number.isNaN(n))
8530
- throw new Error(`--${flag(field.name)} must be a number`);
8531
- return n;
9515
+ function number2(name, raw) {
9516
+ const n = Number(raw);
9517
+ if (raw === "" || Number.isNaN(n)) {
9518
+ throw new UsageError(`--${name} must be a number`);
9519
+ }
9520
+ return n;
9521
+ }
9522
+ function coerce({ field, spec }, raw) {
9523
+ if (spec.kind === "list") {
9524
+ const values = raw;
9525
+ return spec.numbers ? values.map((v) => number2(spec.name, v)) : values;
8532
9526
  }
9527
+ if (spec.kind === "boolean") return raw === true;
9528
+ if (field.type === "number") return number2(spec.name, raw);
8533
9529
  if (field.type === "json") {
8534
9530
  try {
8535
9531
  return JSON.parse(String(raw));
8536
9532
  } catch {
8537
- throw new Error(`--${flag(field.name)} must be JSON`);
9533
+ throw new UsageError(`--${spec.name} must be JSON`);
8538
9534
  }
8539
9535
  }
8540
9536
  return raw;
8541
9537
  }
8542
9538
  async function call2(ctx, op, args, options, flags) {
8543
- const { api: api2, token, workspace: workspace2, environment: environment2 } = ctx.credentials({
8544
- workspace: op.workspace ? options.workspace ?? void 0 : false
8545
- });
8546
- const values = (field) => field.in === "path" || op.cli.args.includes(field.name) ? args[field.name] : options[optionKey(field.name)];
8547
9539
  let whole = {};
8548
9540
  if (op.hasBody && options.data) {
8549
9541
  try {
8550
9542
  whole = JSON.parse(String(options.data));
8551
9543
  } catch {
8552
- throw new Error("--data must be a JSON object");
9544
+ throw new UsageError("--data must be a JSON object");
8553
9545
  }
8554
9546
  }
8555
9547
  const input = {};
8556
9548
  for (const field of op.fields) {
8557
- const raw2 = values(field);
8558
- if (raw2 === void 0) continue;
8559
- input[field.name] = field.in === "body" ? coerce(field, raw2) : raw2;
9549
+ if (field.in === "path" || op.cli.args.includes(field.name)) {
9550
+ if (args[field.name] !== void 0) input[field.name] = args[field.name];
9551
+ }
9552
+ }
9553
+ for (const flagged of flags) {
9554
+ const { field, spec } = flagged;
9555
+ const raw = options[optionKey(spec.name)];
9556
+ const clear = spec.clear && options[optionKey(`clear-${spec.clear}`)];
9557
+ if (clear && raw !== void 0) {
9558
+ throw new UsageError(
9559
+ `pass --${spec.name} or --clear-${spec.clear}, not both`
9560
+ );
9561
+ }
9562
+ if (clear) input[field.name] = null;
9563
+ else if (raw !== void 0) {
9564
+ input[field.name] = field.in === "body" || spec.kind !== "value" ? coerce(flagged, raw) : raw;
9565
+ }
8560
9566
  }
8561
9567
  const missing = flags.filter(
8562
- (field) => field.required && input[field.name] === void 0 && (field.in !== "body" || whole[field.name] === void 0)
9568
+ ({ field }) => field.required && input[field.name] === void 0 && (field.in !== "body" || whole[field.name] === void 0)
8563
9569
  );
8564
9570
  if (missing.length > 0) {
8565
- throw new Error(
8566
- `missing ${missing.map((f) => `--${flag(f.name)}`).join(", ")}`
9571
+ throw new UsageError(
9572
+ `missing ${missing.map(({ spec }) => `--${spec.name}`).join(", ")}`
8567
9573
  );
8568
9574
  }
8569
9575
  const problem = variantProblem(op, input, whole);
8570
- if (problem) throw new Error(problem);
8571
- const request = operationRequest(op, input, whole);
9576
+ if (problem) throw new UsageError(problem);
9577
+ const credentials = ctx.credentials({
9578
+ workspace: op.workspace ? options.workspace ?? void 0 : false
9579
+ });
9580
+ if (op.paginated && options.all === true) {
9581
+ const paged = op.fields.some(
9582
+ (f) => f.in === "query" && f.name === "cursor"
9583
+ );
9584
+ const items = [];
9585
+ let cursor = input.cursor;
9586
+ for (; ; ) {
9587
+ const page = await send(
9588
+ ctx,
9589
+ op,
9590
+ credentials,
9591
+ operationRequest(op, { ...input, cursor }, whole),
9592
+ options
9593
+ );
9594
+ items.push(...page.items);
9595
+ if (!paged || typeof page.nextCursor !== "string") break;
9596
+ cursor = page.nextCursor;
9597
+ }
9598
+ return { items, nextCursor: null };
9599
+ }
9600
+ return send(
9601
+ ctx,
9602
+ op,
9603
+ credentials,
9604
+ operationRequest(op, input, whole),
9605
+ options
9606
+ );
9607
+ }
9608
+ async function send(ctx, op, credentials, request, options) {
9609
+ const { baseURL, token, workspace: workspace2, environment: environment3 } = credentials;
8572
9610
  const headers = {
8573
9611
  authorization: `Bearer ${token}`
8574
9612
  };
8575
9613
  if (workspace2) headers["x-workspace"] = workspace2;
8576
- if (environment2) headers["x-environment"] = environment2;
9614
+ if (environment3) headers["x-environment"] = environment3;
8577
9615
  if (request.body) headers["content-type"] = "application/json";
8578
9616
  const raw = op.rawBody ? readFileSync3(String(options.file)) : void 0;
8579
9617
  if (op.rawBody) headers["content-type"] = op.rawBody;
8580
9618
  const response = await ctx.fetch(
8581
- new Request(`${api2}/v1${request.path}`, {
9619
+ new Request(`${baseURL}/v1${request.path}`, {
8582
9620
  method: request.method,
8583
9621
  headers,
8584
9622
  ...request.body ? { body: JSON.stringify(request.body) } : {},
@@ -8589,16 +9627,13 @@ async function call2(ctx, op, args, options, flags) {
8589
9627
  return new Uint8Array(await response.arrayBuffer());
8590
9628
  }
8591
9629
  const text = await response.text();
8592
- const data = text ? JSON.parse(text) : null;
8593
- if (!response.ok) {
8594
- const error = data?.error;
8595
- throw new ApiError(
8596
- response.status,
8597
- error?.code ?? "internal_error",
8598
- error?.message ?? `HTTP ${response.status}`,
8599
- error?.requestId
8600
- );
9630
+ let data = null;
9631
+ try {
9632
+ data = text ? JSON.parse(text) : null;
9633
+ } catch {
9634
+ if (response.ok) throw new Error("the API's answer is not JSON");
8601
9635
  }
9636
+ if (!response.ok) throw apiErrorFrom(data, response);
8602
9637
  return data;
8603
9638
  }
8604
9639
  function scalarColumns(rows) {
@@ -8623,7 +9658,9 @@ function print(ctx, data, asJson) {
8623
9658
  rows.length === 0 ? "No results." : table(rows, scalarColumns(rows))
8624
9659
  );
8625
9660
  if (typeof page.nextCursor === "string") {
8626
- ctx.io.stdout(`More: --cursor ${page.nextCursor}`);
9661
+ ctx.io.stdout(
9662
+ `More: --cursor ${page.nextCursor}, or --all for every page`
9663
+ );
8627
9664
  }
8628
9665
  return;
8629
9666
  }
@@ -8645,30 +9682,44 @@ function variantProblem(op, input, whole) {
8645
9682
  const chosen = String(input[key] ?? whole[key]);
8646
9683
  const needs = op.variants.required[chosen];
8647
9684
  if (!needs) {
8648
- return `--${flag(key)} must be one of ${Object.keys(op.variants.required).join(", ")}`;
9685
+ return `--${kebab(key)} must be one of ${Object.keys(op.variants.required).join(", ")}`;
8649
9686
  }
8650
9687
  const absent = needs.filter(
8651
9688
  (name) => input[name] === void 0 && whole[name] === void 0
8652
9689
  );
8653
- return absent.length > 0 ? `missing ${absent.map((name) => `--${flag(name)}`).join(", ")} (needed with --${flag(key)} ${chosen})` : void 0;
9690
+ return absent.length > 0 ? `missing ${absent.map((name) => `--${kebab(name)}`).join(", ")} (needed with --${kebab(key)} ${chosen})` : void 0;
8654
9691
  }
8655
9692
 
9693
+ // src/product/index.ts
9694
+ var product_exports2 = {};
9695
+ __export(product_exports2, {
9696
+ productCommands: () => productCommands
9697
+ });
9698
+
8656
9699
  // src/product/check.ts
9700
+ var EXIT_REFUSED = 5;
9701
+ var RefusedError = class extends Error {
9702
+ exitCode = EXIT_REFUSED;
9703
+ constructor() {
9704
+ super("The check was refused");
9705
+ this.name = "RefusedError";
9706
+ }
9707
+ };
8657
9708
  var checkCommand = (program2, ctx) => {
8658
- program2.command("check").description(`Short for \`${brand.name} checks create\``).argument("<subject>", "who is acting, as kind:id (user:usr_123)").argument("<action>", "what they want to do (ai-call)").option("--cost <n>", "units it would use (default 1)").option(
9709
+ program2.command("check").description(`Short for \`${brand.name} checks create\``).argument("<subject>", "who is acting, as kind:id (user:user_123)").argument("<action>", "what they want to do (ai-call)").option("--cost <n>", "units it would use (default 1)").option(
8659
9710
  "--shared <kind:id>",
8660
9711
  "a shared subject it also draws from (a team's pool); repeat for more",
8661
9712
  (value, previous = []) => [...previous, value]
8662
9713
  ).option("--workspace <slug>", "act in this workspace for one call").option("--json", "the decision as the API answers it").addHelpText(
8663
9714
  "after",
8664
9715
  `
8665
- Example: ${brand.name} check user:usr_123 ai-call --cost 5
8666
- A refusal exits 0: it's an answer. Errors exit 1.`
9716
+ Example: ${brand.name} check user:user_123 ai-call --cost 5
9717
+ Exit codes: 0 allowed, 5 refused, 2 wrong usage, 1 any other failure.`
8667
9718
  ).action(
8668
9719
  async (subject, action, options) => {
8669
9720
  const cost = options.cost === void 0 ? void 0 : Number(options.cost);
8670
9721
  if (cost !== void 0 && !Number.isInteger(cost)) {
8671
- throw new Error("--cost must be a whole number");
9722
+ throw new UsageError("--cost must be a whole number");
8672
9723
  }
8673
9724
  const decision = await ctx.client({ workspace: options.workspace }).checks.create(
8674
9725
  {
@@ -8676,24 +9727,25 @@ A refusal exits 0: it's an answer. Errors exit 1.`
8676
9727
  action,
8677
9728
  ...cost !== void 0 ? { cost } : {},
8678
9729
  ...options.shared?.length ? { shared: options.shared.map(parseSubject) } : {}
8679
- },
8680
- { idempotencyKey: crypto.randomUUID() }
9730
+ }
9731
+ // No key here: the client sends one, or the global
9732
+ // --idempotency-key's, for every write.
8681
9733
  );
8682
- if (!decision) throw new Error("Limitry answered without a decision");
8683
9734
  ctx.io.stdout(options.json ? json(decision) : answer(decision));
9735
+ if (!decision.allowed) throw new RefusedError();
8684
9736
  }
8685
9737
  );
8686
9738
  };
8687
9739
  function parseSubject(value) {
8688
9740
  const at = value.indexOf(":");
8689
9741
  if (at <= 0 || at === value.length - 1) {
8690
- throw new Error(
8691
- `"${value}": write a subject as kind:id, e.g. user:usr_123`
9742
+ throw new UsageError(
9743
+ `"${value}": write a subject as kind:id, e.g. user:user_123`
8692
9744
  );
8693
9745
  }
8694
9746
  return { kind: value.slice(0, at), id: value.slice(at + 1) };
8695
9747
  }
8696
- var left = (r) => `${r.name}: ${r.remaining} ${r.unit} left${r.resetsAt ? `, resets ${r.resetsAt}` : ""}`;
9748
+ var left = (r) => `${r.limitName}: ${r.remaining} ${r.unit} left${r.resetsAt ? `, resets ${r.resetsAt}` : ""}`;
8697
9749
  function answer(decision) {
8698
9750
  if (decision.allowed) {
8699
9751
  return decision.limits.length === 0 ? "Allowed. No limit applies." : `Allowed. ${decision.limits.map(left).join("; ")}`;
@@ -8723,26 +9775,36 @@ Shortcut: \`${brand.name} sync\`, the same command.`
8723
9775
  );
8724
9776
  };
8725
9777
  function syncCommand(command, ctx, description, more) {
8726
- command.description(description).argument("[file]", "the file to read", "limitry.json").option("--preview", "show what would change, and change nothing").option("--limits <json>", "the limits as a JSON array, instead of a file").option(
9778
+ command.description(description).argument("[file]", "the file to read, or - for stdin", "limitry.json").option("--dry-run", "show what would change, and change nothing").option(
8727
9779
  "--data <json>",
8728
9780
  "the whole JSON body, as every command takes, instead of a file"
8729
9781
  ).option(
8730
9782
  "--archive-missing",
8731
9783
  "archive active limits the file doesn't name (restorable)"
9784
+ ).option(
9785
+ "--source <label>",
9786
+ "where the limits come from, named on each one in the app (default: the file's name)"
8732
9787
  ).option("--workspace <slug>", "act in this workspace for one call").option("--json", "machine-readable output").addHelpText(
8733
9788
  "after",
8734
- '\nThe file: { "limits": [ { "name": "AI budget", "subject": { "kind": "user" }, "action": "ai-call", "amount": 200, "unit": "cents", "window": "month" } ] }\nEach limit is described whole: a field left out is its default, as on `limits create`. Names are the key.\nWhat a limit counts (subject, action, unit, window, every, start, rolling) is fixed: to change it, give the entry a new name.' + more
9789
+ '\nThe file: { "limits": [ { "name": "AI budget", "subject": { "kind": "user" }, "action": "ai-call", "amount": 200, "unit": "cents", "window": "month" } ] }\nOptional: "kinds": [ { "kind": "cost-center", "displayName": "Cost center", "plural": "Cost centers" } ], top level first, names your kinds in the app.\nEach limit is described whole: a field left out is its default, as on `limits create`. Names are the key.\nWhat a limit counts (subject, action, unit, window, every, start, rolling) is fixed: to change it, give the entry a new name.\nWhat the sync sets is locked in the app, which names the file (or --source) on each limit.' + more
8735
9790
  ).action(
8736
9791
  async (file, options) => {
8737
9792
  const data = options.data === void 0 ? {} : parseData(options.data);
8738
- const limits = options.limits !== void 0 ? parseLimits(options.limits, "--limits") : data.limits !== void 0 ? limitsIn(data.limits) : readLimitsFile(file);
9793
+ const fromStdin = file === "-";
9794
+ const fromFile = data.limits !== void 0 ? null : fromStdin ? parseSyncFile(await ctx.io.stdin(), "stdin") : readSyncFile(file);
9795
+ const limits = data.limits !== void 0 ? limitsIn(data.limits) : fromFile.limits;
9796
+ const kinds = data.kinds !== void 0 ? data.kinds : fromFile?.kinds;
9797
+ const source = options.source ?? (typeof data.source === "string" ? data.source : void 0) ?? (fromFile && !fromStdin ? file : void 0);
8739
9798
  const result = await ctx.client({ workspace: options.workspace }).limits.sync(
8740
9799
  {
8741
9800
  limits,
8742
9801
  archiveMissing: options.archiveMissing ?? data.archiveMissing === true,
8743
- preview: options.preview ?? data.preview === true
8744
- },
8745
- { idempotencyKey: crypto.randomUUID() }
9802
+ dryRun: options.dryRun ?? data.dryRun === true,
9803
+ ...kinds !== void 0 ? { kinds } : {},
9804
+ ...source !== void 0 ? { source } : {}
9805
+ }
9806
+ // No key here: the client sends one, or the global
9807
+ // --idempotency-key's, for every write.
8746
9808
  );
8747
9809
  if (options.json) {
8748
9810
  ctx.io.stdout(json(result));
@@ -8752,7 +9814,7 @@ function syncCommand(command, ctx, description, more) {
8752
9814
  }
8753
9815
  );
8754
9816
  }
8755
- function readLimitsFile(file) {
9817
+ function readSyncFile(file) {
8756
9818
  const path2 = resolve(file);
8757
9819
  let text;
8758
9820
  try {
@@ -8760,6 +9822,9 @@ function readLimitsFile(file) {
8760
9822
  } catch (error) {
8761
9823
  throw new Error(`${file}: no such file`, { cause: error });
8762
9824
  }
9825
+ return parseSyncFile(text, file);
9826
+ }
9827
+ function parseSyncFile(text, file) {
8763
9828
  let parsed;
8764
9829
  try {
8765
9830
  parsed = JSON.parse(text);
@@ -8768,25 +9833,17 @@ function readLimitsFile(file) {
8768
9833
  cause: error
8769
9834
  });
8770
9835
  }
8771
- const limits = parsed?.limits;
8772
- if (!Array.isArray(limits)) {
9836
+ const body = parsed;
9837
+ if (!Array.isArray(body?.limits)) {
8773
9838
  throw new Error(`${file}: expected { "limits": [ \u2026 ] }`);
8774
9839
  }
8775
- return limits;
8776
- }
8777
- function parseLimits(text, flag2) {
8778
- let parsed;
8779
- try {
8780
- parsed = JSON.parse(text);
8781
- } catch (error) {
8782
- throw new Error(`${flag2} must be a JSON array of limits`, {
8783
- cause: error
8784
- });
8785
- }
8786
- if (!Array.isArray(parsed)) {
8787
- throw new Error(`${flag2} must be a JSON array of limits`);
9840
+ if (body.kinds !== void 0 && !Array.isArray(body.kinds)) {
9841
+ throw new Error(`${file}: "kinds" must be a list, top level first`);
8788
9842
  }
8789
- return parsed;
9843
+ return {
9844
+ limits: body.limits,
9845
+ ...body.kinds !== void 0 ? { kinds: body.kinds } : {}
9846
+ };
8790
9847
  }
8791
9848
  function parseData(text) {
8792
9849
  let parsed;
@@ -8808,7 +9865,7 @@ function limitsIn(value) {
8808
9865
  }
8809
9866
  var show = (value) => typeof value === "string" ? value : JSON.stringify(value);
8810
9867
  function summary(result) {
8811
- const dry = result.preview;
9868
+ const dry = result.dryRun;
8812
9869
  const lines = [
8813
9870
  ...result.created.map(
8814
9871
  (name) => `${dry ? "Would create" : "Created"}: ${name}`
@@ -8821,6 +9878,16 @@ function summary(result) {
8821
9878
  (name) => `${dry ? "Would archive" : "Archived"}: ${name}`
8822
9879
  )
8823
9880
  ];
9881
+ for (const r of result.restored ?? [])
9882
+ lines.push(
9883
+ `${dry ? "Would restore" : "Restored"} the file's values over an override: ${r.name} (${r.reason})`
9884
+ );
9885
+ if (result.kinds?.restored)
9886
+ lines.push(
9887
+ dry ? "Would restore the kinds over an override." : "Restored the kinds over an override."
9888
+ );
9889
+ if (result.kinds?.changed)
9890
+ lines.push(dry ? "Would update the kinds." : "Updated the kinds.");
8824
9891
  const same2 = result.unchanged.length;
8825
9892
  if (lines.length === 0) {
8826
9893
  return [
@@ -8828,7 +9895,7 @@ function summary(result) {
8828
9895
  ];
8829
9896
  }
8830
9897
  if (same2 > 0) lines.push(`Unchanged: ${same2}`);
8831
- if (dry) lines.push("Preview: nothing was changed.");
9898
+ if (dry) lines.push("Dry run: nothing was changed.");
8832
9899
  return lines;
8833
9900
  }
8834
9901
 
@@ -8846,15 +9913,18 @@ var commands = [
8846
9913
  function tokenEnvVar() {
8847
9914
  return `${brand.identifier.toUpperCase()}_TOKEN`;
8848
9915
  }
9916
+ var VERSION2 = "1.0.0-rc.19";
8849
9917
  function build(io) {
8850
9918
  let actedIn = null;
8851
9919
  let sending;
8852
- const program2 = new Command().name(brand.name).description(`The ${brand.productName} CLI`).version("1.0.0-rc.16").addHelpText(
9920
+ const program2 = new Command().name(brand.name).description(`The ${brand.productName} CLI`).version(VERSION2).addHelpText(
8853
9921
  "after",
8854
9922
  `
8855
9923
  Token: \`${brand.name} login\` stores it in ~/.config/${brand.name}/; ${tokenEnvVar()} overrides.
8856
- Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} environment use\`, else the default.`
8857
- ).option(
9924
+ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} environment use\`, else the default.
9925
+ API: --base-url, else ${baseURLEnvVar()}, else the one \`${brand.name} login --base-url\` saved.
9926
+ Exit codes: 0 success, 1 failure, 2 wrong usage, 4 not logged in.`
9927
+ ).option("--base-url <url>", "the API's origin, without /v1").option(
8858
9928
  "--environment <name>",
8859
9929
  "act in this environment (where the product has them)"
8860
9930
  ).option(
@@ -8866,13 +9936,15 @@ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} en
8866
9936
  }).showHelpAfterError();
8867
9937
  const ctx = {
8868
9938
  io,
8869
- settings: () => resolveSettings(io.env, io.homeDir, {
8870
- environment: program2.opts().environment
8871
- }),
9939
+ settings: () => resolveSettings(
9940
+ io.env,
9941
+ io.homeDir,
9942
+ program2.opts()
9943
+ ),
8872
9944
  credentials: (options = {}) => {
8873
9945
  const settings = ctx.settings();
8874
9946
  if (!settings.token) {
8875
- throw new Error(
9947
+ throw new NotLoggedInError(
8876
9948
  `not logged in. Run \`${brand.name} login\` or set ${tokenEnvVar()}.`
8877
9949
  );
8878
9950
  }
@@ -8883,7 +9955,7 @@ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} en
8883
9955
  );
8884
9956
  }
8885
9957
  return {
8886
- api: settings.api,
9958
+ baseURL: settings.baseURL,
8887
9959
  token: settings.token,
8888
9960
  workspace: void 0,
8889
9961
  environment: settings.environment
@@ -8896,7 +9968,7 @@ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} en
8896
9968
  );
8897
9969
  }
8898
9970
  return {
8899
- api: settings.api,
9971
+ baseURL: settings.baseURL,
8900
9972
  token: settings.token,
8901
9973
  workspace: workspace2,
8902
9974
  environment: settings.environment
@@ -8910,7 +9982,7 @@ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} en
8910
9982
  maxRetries: 0
8911
9983
  })
8912
9984
  ),
8913
- fetch: (request) => {
9985
+ fetch: async (request) => {
8914
9986
  sending ??= withRetries(
8915
9987
  async (attempt) => {
8916
9988
  const response = await io.fetch(attempt);
@@ -8923,7 +9995,14 @@ Environment: --environment, else ${environmentEnvVar()}, else \`${brand.name} en
8923
9995
  )
8924
9996
  }
8925
9997
  );
8926
- return sending(request);
9998
+ const headers = new Headers(request.headers);
9999
+ headers.set("user-agent", `${brand.name}-cli/${VERSION2}`);
10000
+ const named = new Request(request, { headers });
10001
+ try {
10002
+ return await sending(named);
10003
+ } catch (error) {
10004
+ throw connectionErrorFrom(error, request.signal);
10005
+ }
8927
10006
  }
8928
10007
  };
8929
10008
  for (const register2 of commands) register2(program2, ctx);
@@ -8933,35 +10012,67 @@ async function run(argv, io) {
8933
10012
  const { program: program2, actedIn } = build(io);
8934
10013
  try {
8935
10014
  await program2.parseAsync(argv, { from: "user" });
8936
- const environment2 = actedIn();
8937
- if (environment2) io.stderr(`Environment: ${environment2}`);
8938
- return 0;
10015
+ const environment3 = actedIn();
10016
+ if (environment3) io.stderr(`Environment: ${environment3}`);
10017
+ return EXIT.ok;
8939
10018
  } catch (error) {
8940
- const environment2 = actedIn();
8941
- if (error instanceof CommanderError) return error.exitCode;
10019
+ const environment3 = actedIn();
10020
+ if (error instanceof CommanderError) {
10021
+ return error.exitCode === 0 ? EXIT.ok : EXIT.usage;
10022
+ }
10023
+ const code2 = exitCode(error);
8942
10024
  if (argv.includes("--json")) {
8943
10025
  io.stderr(
8944
10026
  JSON.stringify({
8945
- error: error instanceof ApiError ? {
10027
+ error: error instanceof APIError ? {
8946
10028
  code: error.code,
8947
10029
  message: error.message,
8948
10030
  status: error.status,
8949
- ...error.requestId ? { requestId: error.requestId } : {}
8950
- } : { code: "cli_error", message: error.message },
8951
- ...environment2 ? { environment: environment2 } : {}
10031
+ ...error.requestId ? { requestId: error.requestId } : {},
10032
+ ...error.docs ? { docs: error.docs } : {},
10033
+ ...error.details ? { details: error.details } : {}
10034
+ } : {
10035
+ code: code2 === EXIT.usage ? "usage_error" : code2 === EXIT.auth ? "not_logged_in" : "cli_error",
10036
+ message: error.message
10037
+ },
10038
+ ...environment3 ? { environment: environment3 } : {}
8952
10039
  })
8953
10040
  );
8954
- return 1;
10041
+ return code2;
8955
10042
  }
8956
- if (error instanceof ApiError) {
10043
+ if (error instanceof APIError) {
8957
10044
  const requestId = error.requestId ? ` [request ${error.requestId}]` : "";
8958
10045
  io.stderr(`${brand.name}: ${error.message} (${error.code})${requestId}`);
10046
+ for (const detail of error.details ?? []) {
10047
+ io.stderr(
10048
+ ` ${detail.path ? `${detail.path}: ` : ""}${detail.message}`
10049
+ );
10050
+ }
10051
+ const hint = scopeHint(error);
10052
+ if (hint) io.stderr(hint);
10053
+ if (error.docs) io.stderr(`See ${error.docs}`);
8959
10054
  } else {
8960
- io.stderr(`${brand.name}: ${error.message}`);
10055
+ const cause = error instanceof APIConnectionError && error.cause instanceof Error ? ` (${error.cause.message})` : "";
10056
+ io.stderr(`${brand.name}: ${error.message}${cause}`);
8961
10057
  }
8962
- if (environment2) io.stderr(`Environment: ${environment2}`);
8963
- return 1;
10058
+ if (environment3) io.stderr(`Environment: ${environment3}`);
10059
+ return code2;
10060
+ }
10061
+ }
10062
+ function exitCode(error) {
10063
+ if (error instanceof AuthenticationError || error?.cause instanceof AuthenticationError) {
10064
+ return EXIT.auth;
8964
10065
  }
10066
+ const own = error?.exitCode;
10067
+ return typeof own === "number" && !(error instanceof APIError) ? own : EXIT.failure;
10068
+ }
10069
+ function scopeHint(error) {
10070
+ const own = Reflect.get(product_exports2, "productErrorHint");
10071
+ const mine = own?.(error);
10072
+ if (mine) return mine;
10073
+ const scope = /not granted the ([\w.:-]+) scope/.exec(error.message)?.[1];
10074
+ if (error.code !== "forbidden" || !scope) return null;
10075
+ return `Sign in again with \`${brand.name} login\` and choose access that includes ${scope}.`;
8965
10076
  }
8966
10077
 
8967
10078
  // src/main.ts