@r-33/opencode 0.4.7-rc.29 → 0.4.7-rc.31

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.
@@ -90,6 +90,146 @@ var parseManagementSubject = (credential) => {
90
90
  return subject;
91
91
  };
92
92
 
93
+ // src/attribution/read-legacy-key/read-legacy-key.ts
94
+ import * as path from "node:path";
95
+ var LEGACY_KEY_RELATIVE_PATH = path.join(".opencode", "route33.key");
96
+
97
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
98
+ var readOrgId = (value) => {
99
+ const orgId = value["orgId"];
100
+ if (orgId === void 0) {
101
+ return void 0;
102
+ }
103
+ if (typeof orgId !== "string") {
104
+ throw new ContractParseError("invalid attribution");
105
+ }
106
+ return orgId;
107
+ };
108
+
109
+ // src/attribution/parse-attribution/parse-attribution.ts
110
+ var parseAttribution = (value) => {
111
+ if (!isRecord(value)) {
112
+ throw new ContractParseError("invalid attribution");
113
+ }
114
+ const orgId = readOrgId(value);
115
+ const binding = (() => {
116
+ const { boundKeyId, boundScopeId } = value;
117
+ if (boundKeyId === void 0 && boundScopeId === void 0) return {};
118
+ if (typeof boundKeyId !== "string" || !boundKeyId)
119
+ throw new ContractParseError("invalid bound key id");
120
+ if (boundScopeId === void 0) return { boundKeyId };
121
+ if (typeof boundScopeId !== "string" || !/^[a-f0-9]{64}$/u.test(boundScopeId))
122
+ throw new ContractParseError("invalid bound scope id");
123
+ return { boundKeyId, boundScopeId };
124
+ })();
125
+ if (value["kind"] === "personal") {
126
+ return { ...binding, kind: "personal", orgId };
127
+ }
128
+ if (value["kind"] === "project" && typeof value["projectId"] === "string") {
129
+ return {
130
+ ...binding,
131
+ kind: "project",
132
+ ...orgId === void 0 ? {} : { orgId },
133
+ projectId: value["projectId"]
134
+ };
135
+ }
136
+ throw new ContractParseError("invalid attribution");
137
+ };
138
+
139
+ // src/attribution/remove-legacy-key/remove-legacy-key.ts
140
+ import * as path2 from "node:path";
141
+ var LEGACY_KEY_RELATIVE_PATH2 = path2.join(".opencode", "route33.key");
142
+
143
+ // src/key-lease/lease-state/lease-state.ts
144
+ var LeaseState = class _LeaseState {
145
+ /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
146
+ #current;
147
+ constructor(current) {
148
+ this.#current = current;
149
+ }
150
+ /** Restores untrusted persisted metadata or an empty lease.
151
+ * @param value - Persisted metadata, or undefined for a new installation.
152
+ * @returns A lease-state coordinator.
153
+ */
154
+ static restore(value) {
155
+ if (value === void 0) {
156
+ return new _LeaseState(void 0);
157
+ }
158
+ if (!isRecord(value)) {
159
+ throw new ContractParseError("invalid gateway key lease state");
160
+ }
161
+ const fields = Object.keys(value);
162
+ if (fields.some(
163
+ (field) => !["attribution", "expiresAt", "keyId", "wizardRequest"].includes(
164
+ field
165
+ )
166
+ )) {
167
+ throw new ContractParseError("invalid gateway key lease state");
168
+ }
169
+ const expiresAt = value["expiresAt"];
170
+ const keyId = value["keyId"];
171
+ const wizardRequest = value["wizardRequest"];
172
+ if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0 || wizardRequest !== void 0 && typeof wizardRequest !== "string") {
173
+ throw new ContractParseError("invalid gateway key lease state");
174
+ }
175
+ return new _LeaseState({
176
+ attribution: parseAttribution(value["attribution"]),
177
+ expiresAt,
178
+ keyId,
179
+ wizardRequest
180
+ });
181
+ }
182
+ /** Reads the current non-secret metadata.
183
+ * @returns The current lease metadata, if one is committed.
184
+ */
185
+ snapshot() {
186
+ return this.#current;
187
+ }
188
+ /** Checks whether current metadata belongs to an attribution.
189
+ * @param attribution - The requested ownership choice.
190
+ * @returns Whether the current lease has the same attribution.
191
+ */
192
+ matchesAttribution(attribution) {
193
+ if (this.#current === void 0) {
194
+ return false;
195
+ }
196
+ switch (this.#current.attribution.kind) {
197
+ case "personal":
198
+ return attribution.kind === "personal";
199
+ case "project":
200
+ return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
201
+ default:
202
+ return _LeaseState.#unexpectedAttribution(this.#current.attribution);
203
+ }
204
+ }
205
+ /** Atomically swaps metadata when the expected snapshot is still current.
206
+ * @param expected - Snapshot observed before asynchronous renewal.
207
+ * @param next - Fresh metadata to commit.
208
+ * @returns Whether the swap committed.
209
+ */
210
+ compareAndSwap(expected, next) {
211
+ if (this.#current !== expected) {
212
+ return false;
213
+ }
214
+ this.#current = next;
215
+ return true;
216
+ }
217
+ /** Clears metadata only while the expected snapshot remains current.
218
+ * @param expected - Snapshot whose lease is being invalidated.
219
+ * @returns Whether the state was cleared.
220
+ */
221
+ clear(expected) {
222
+ if (this.#current !== expected) {
223
+ return false;
224
+ }
225
+ this.#current = void 0;
226
+ return true;
227
+ }
228
+ static #unexpectedAttribution(value) {
229
+ throw new TypeError(`Unexpected attribution: ${String(value)}`);
230
+ }
231
+ };
232
+
93
233
  // src/key-lease/key-lease-error/key-lease-error.ts
94
234
  var REDACTED_CAUSE = "Route 33 gateway key lease dependency failed";
95
235
  var KeyLeaseError = class extends Error {
@@ -100,9 +240,11 @@ var KeyLeaseError = class extends Error {
100
240
  );
101
241
  this.code = code;
102
242
  this.name = "KeyLeaseError";
243
+ this.rejection = options?.rejection;
103
244
  this.statusCode = options?.statusCode;
104
245
  }
105
246
  code;
247
+ rejection;
106
248
  statusCode;
107
249
  };
108
250
 
@@ -253,9 +395,62 @@ var buildMintInput = (deps) => {
253
395
  };
254
396
  };
255
397
 
398
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
399
+ var commitStagedReplacement = async (stage, save, persist) => {
400
+ const storeFailure = (cause) => {
401
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
402
+ };
403
+ const staged = await stage().catch(storeFailure);
404
+ try {
405
+ save();
406
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
407
+ } finally {
408
+ await staged?.discard();
409
+ }
410
+ };
411
+
412
+ // src/management/management-error/management-error.ts
413
+ var ManagementError = class extends Error {
414
+ constructor(code, options) {
415
+ super(
416
+ "Route 33 management request failed",
417
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
418
+ );
419
+ this.code = code;
420
+ this.name = "ManagementError";
421
+ this.rejection = options?.rejection;
422
+ this.statusCode = options?.statusCode;
423
+ }
424
+ code;
425
+ rejection;
426
+ statusCode;
427
+ };
428
+
429
+ // src/key-lease/mint-failure/mint-failure.ts
430
+ var mintFailure = (cause) => {
431
+ const response = cause instanceof ManagementError ? cause : void 0;
432
+ return new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
433
+ cause,
434
+ ...response?.rejection === void 0 ? {} : { rejection: response.rejection },
435
+ ...response?.statusCode === void 0 ? {} : { statusCode: response.statusCode }
436
+ });
437
+ };
438
+
256
439
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
257
440
  var mintFreshLease = async (deps) => {
258
441
  const now = deps.clock();
442
+ const current = deps.state.snapshot();
443
+ const reusable = () => {
444
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
445
+ return { key: deps.storedKey, lease: current };
446
+ }
447
+ return void 0;
448
+ };
449
+ const reused = reusable();
450
+ if (reused !== void 0) {
451
+ deps.saveAttribution?.();
452
+ return reused;
453
+ }
259
454
  const input = buildMintInput({
260
455
  attribution: deps.attribution,
261
456
  extras: deps.extras,
@@ -271,20 +466,30 @@ var mintFreshLease = async (deps) => {
271
466
  input
272
467
  );
273
468
  } catch (cause) {
274
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
469
+ throw mintFailure(cause);
275
470
  }
276
471
  const minted = {
277
472
  key: material.key,
278
473
  lease: {
279
474
  attribution: deps.attribution,
280
475
  expiresAt: material.expires_at,
281
- keyId: material.id
476
+ keyId: material.id,
477
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
282
478
  }
283
479
  };
284
- try {
285
- await deps.secretStore.set(minted.key);
286
- } catch (cause) {
480
+ const storeFailure = (cause) => {
287
481
  throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
482
+ };
483
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
484
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
485
+ await commitStagedReplacement(
486
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
487
+ deps.saveAttribution,
488
+ persist
489
+ );
490
+ } else {
491
+ await persist().catch(storeFailure);
492
+ deps.saveAttribution?.();
288
493
  }
289
494
  deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
290
495
  return minted;
@@ -344,21 +549,6 @@ var rejectLease = async (options) => {
344
549
  }
345
550
  };
346
551
 
347
- // src/management/management-error/management-error.ts
348
- var ManagementError = class extends Error {
349
- constructor(code, options) {
350
- super(
351
- "Route 33 management request failed",
352
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
353
- );
354
- this.code = code;
355
- this.name = "ManagementError";
356
- this.statusCode = options?.statusCode;
357
- }
358
- code;
359
- statusCode;
360
- };
361
-
362
552
  // src/key-lease/mint-key/mint-key.ts
363
553
  var mintKey = async (options) => {
364
554
  const now = options.clock();
@@ -392,10 +582,7 @@ var mintKey = async (options) => {
392
582
  if (isManagementUnauthorized(cause)) {
393
583
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
394
584
  }
395
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
396
- cause,
397
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
398
- });
585
+ throw mintFailure(cause);
399
586
  }
400
587
  return {
401
588
  key: material.key,
@@ -461,7 +648,7 @@ var renewKey = async (options) => {
461
648
  }
462
649
  }
463
650
  try {
464
- await options.secretStore.set(renewed.key);
651
+ await options.secretStore.set(renewed.key, renewed.lease);
465
652
  } catch (cause) {
466
653
  const cleared = await discard(renewed.lease.keyId);
467
654
  if (!cleared) {
@@ -581,7 +768,10 @@ var leaseForAttribution = async (options) => {
581
768
  secretStore: options.installation.secretStore,
582
769
  state: options.installation.state,
583
770
  stateStore: options.installation.stateStore,
584
- ttlMs: policy.ttlMs
771
+ ttlMs: policy.ttlMs,
772
+ wizardRequest: options.request.wizardRequest,
773
+ saveAttribution: options.request.saveAttribution,
774
+ storedKey
585
775
  });
586
776
  }
587
777
  const reusable = reusableLease({
@@ -632,131 +822,6 @@ var leaseForAttribution = async (options) => {
632
822
  }
633
823
  };
634
824
 
635
- // src/attribution/read-legacy-key/read-legacy-key.ts
636
- import * as path from "node:path";
637
- var LEGACY_KEY_RELATIVE_PATH = path.join(".opencode", "route33.key");
638
-
639
- // src/attribution/parse-attribution/read-org-id/read-org-id.ts
640
- var readOrgId = (value) => {
641
- const orgId = value["orgId"];
642
- if (orgId === void 0) {
643
- return void 0;
644
- }
645
- if (typeof orgId !== "string") {
646
- throw new ContractParseError("invalid attribution");
647
- }
648
- return orgId;
649
- };
650
-
651
- // src/attribution/parse-attribution/parse-attribution.ts
652
- var parseAttribution = (value) => {
653
- if (!isRecord(value)) {
654
- throw new ContractParseError("invalid attribution");
655
- }
656
- const orgId = readOrgId(value);
657
- if (value["kind"] === "personal") {
658
- return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
659
- }
660
- if (value["kind"] === "project" && typeof value["projectId"] === "string") {
661
- return {
662
- kind: "project",
663
- ...orgId === void 0 ? {} : { orgId },
664
- projectId: value["projectId"]
665
- };
666
- }
667
- throw new ContractParseError("invalid attribution");
668
- };
669
-
670
- // src/attribution/remove-legacy-key/remove-legacy-key.ts
671
- import * as path2 from "node:path";
672
- var LEGACY_KEY_RELATIVE_PATH2 = path2.join(".opencode", "route33.key");
673
-
674
- // src/key-lease/lease-state/lease-state.ts
675
- var LeaseState = class _LeaseState {
676
- /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
677
- #current;
678
- constructor(current) {
679
- this.#current = current;
680
- }
681
- /** Restores untrusted persisted metadata or an empty lease.
682
- * @param value - Persisted metadata, or undefined for a new installation.
683
- * @returns A lease-state coordinator.
684
- */
685
- static restore(value) {
686
- if (value === void 0) {
687
- return new _LeaseState(void 0);
688
- }
689
- if (!isRecord(value)) {
690
- throw new ContractParseError("invalid gateway key lease state");
691
- }
692
- const fields = Object.keys(value);
693
- if (fields.length !== 3 || fields.some(
694
- (field) => field !== "attribution" && field !== "expiresAt" && field !== "keyId"
695
- )) {
696
- throw new ContractParseError("invalid gateway key lease state");
697
- }
698
- const expiresAt = value["expiresAt"];
699
- const keyId = value["keyId"];
700
- if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0) {
701
- throw new ContractParseError("invalid gateway key lease state");
702
- }
703
- return new _LeaseState({
704
- attribution: parseAttribution(value["attribution"]),
705
- expiresAt,
706
- keyId
707
- });
708
- }
709
- /** Reads the current non-secret metadata.
710
- * @returns The current lease metadata, if one is committed.
711
- */
712
- snapshot() {
713
- return this.#current;
714
- }
715
- /** Checks whether current metadata belongs to an attribution.
716
- * @param attribution - The requested ownership choice.
717
- * @returns Whether the current lease has the same attribution.
718
- */
719
- matchesAttribution(attribution) {
720
- if (this.#current === void 0) {
721
- return false;
722
- }
723
- switch (this.#current.attribution.kind) {
724
- case "personal":
725
- return attribution.kind === "personal";
726
- case "project":
727
- return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
728
- default:
729
- return _LeaseState.#unexpectedAttribution(this.#current.attribution);
730
- }
731
- }
732
- /** Atomically swaps metadata when the expected snapshot is still current.
733
- * @param expected - Snapshot observed before asynchronous renewal.
734
- * @param next - Fresh metadata to commit.
735
- * @returns Whether the swap committed.
736
- */
737
- compareAndSwap(expected, next) {
738
- if (this.#current !== expected) {
739
- return false;
740
- }
741
- this.#current = next;
742
- return true;
743
- }
744
- /** Clears metadata only while the expected snapshot remains current.
745
- * @param expected - Snapshot whose lease is being invalidated.
746
- * @returns Whether the state was cleared.
747
- */
748
- clear(expected) {
749
- if (this.#current !== expected) {
750
- return false;
751
- }
752
- this.#current = void 0;
753
- return true;
754
- }
755
- static #unexpectedAttribution(value) {
756
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
757
- }
758
- };
759
-
760
825
  // src/management/drain-pages/drain-pages.ts
761
826
  var drainPages = async (fetchPage) => {
762
827
  const first = await fetchPage("");
@@ -770,12 +835,6 @@ var drainPages = async (fetchPage) => {
770
835
  return { data, page: { ...page, has_more: false, next_cursor: null } };
771
836
  };
772
837
 
773
- // src/management/sdk-management-keys/sdk-management-keys.ts
774
- import {
775
- createRoute33Client,
776
- Route33SdkError
777
- } from "@r-33/sdk";
778
-
779
838
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
780
839
  var parseApiKey = (value) => {
781
840
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -801,6 +860,7 @@ var parseApiKey = (value) => {
801
860
  name: field("name"),
802
861
  org_id: field("org_id"),
803
862
  ownership_type: value["ownership_type"],
863
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
804
864
  project_id: value["project_id"],
805
865
  revoked: value["revoked"] === true,
806
866
  status
@@ -1036,6 +1096,44 @@ var parseUserMemberships = (value) => {
1036
1096
  };
1037
1097
  };
1038
1098
 
1099
+ // src/management/key-read-operations/key-read-operations.ts
1100
+ var keyReadOperations = (call) => {
1101
+ const withCursor = (cursor) => ({ request }) => {
1102
+ const url = new URL(request.url);
1103
+ url.searchParams.set("cursor", cursor);
1104
+ return new Request(url, request);
1105
+ };
1106
+ const parsePage = (page) => {
1107
+ const collection = parseCollection(page, (row) => row);
1108
+ const data = collection.data.flatMap((row) => {
1109
+ try {
1110
+ return [parseApiKey(row)];
1111
+ } catch (error) {
1112
+ if (error instanceof ContractParseError) return [];
1113
+ throw error;
1114
+ }
1115
+ });
1116
+ return { ...collection, data };
1117
+ };
1118
+ return {
1119
+ get: async (accessToken, id, orgId) => parseApiKey(
1120
+ await call(
1121
+ accessToken,
1122
+ orgId,
1123
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
1124
+ params: { path: { api_key_id: id } }
1125
+ })
1126
+ )
1127
+ ),
1128
+ list: (accessToken, orgId) => drainPages(
1129
+ (cursor) => call(accessToken, orgId, (client) => {
1130
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
1131
+ return client.GET("/api/v1/api-keys", {});
1132
+ }).then(parsePage)
1133
+ )
1134
+ };
1135
+ };
1136
+
1039
1137
  // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
1040
1138
  var buildMintRequestBody = (input) => ({
1041
1139
  ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
@@ -1049,10 +1147,183 @@ var buildMintRequestBody = (input) => ({
1049
1147
  ...input.projectId === null ? {} : { project_id: input.projectId }
1050
1148
  });
1051
1149
 
1052
- // src/management/sdk-management-keys/sdk-management-keys.ts
1150
+ // src/management/key-write-operations/key-write-operations.ts
1151
+ var keyWriteOperations = (call) => ({
1152
+ create: async (accessToken, input) => parseKeyMaterial(
1153
+ await call(
1154
+ accessToken,
1155
+ input.activeOrgId,
1156
+ (client) => client.POST("/api/v1/api-keys", {
1157
+ body: buildMintRequestBody(input)
1158
+ })
1159
+ )
1160
+ ),
1161
+ delete: async (accessToken, id) => {
1162
+ await call(
1163
+ accessToken,
1164
+ void 0,
1165
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
1166
+ params: { path: { api_key_id: id } }
1167
+ })
1168
+ );
1169
+ },
1170
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
1171
+ await call(
1172
+ accessToken,
1173
+ orgId,
1174
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
1175
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
1176
+ params: { path: { api_key_id: id } }
1177
+ })
1178
+ )
1179
+ ),
1180
+ update: async (accessToken, id, input) => parseApiKey(
1181
+ await call(
1182
+ accessToken,
1183
+ void 0,
1184
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
1185
+ body: {
1186
+ budget_currency: "EUR",
1187
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
1188
+ ...input.name === void 0 ? {} : { name: input.name }
1189
+ },
1190
+ params: { path: { api_key_id: id } }
1191
+ })
1192
+ )
1193
+ )
1194
+ });
1195
+
1196
+ // src/management/client-model-id/client-model-id.ts
1197
+ var clientModelId = (offeringId) => {
1198
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
1199
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
1200
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
1201
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
1202
+ };
1203
+
1204
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
1205
+ var catalogRowChoices = (row) => {
1206
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
1207
+ throw new ContractParseError("invalid model catalog item");
1208
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
1209
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
1210
+ return row.offerings.flatMap((offering) => {
1211
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
1212
+ return [];
1213
+ const id = clientModelId(offering.id);
1214
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
1215
+ });
1216
+ };
1217
+
1218
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
1219
+ var exposedCatalogModels = async (readPage) => {
1220
+ const readRows = async (offset2) => {
1221
+ const page = await readPage(offset2);
1222
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
1223
+ throw new ContractParseError("invalid model catalog page");
1224
+ }
1225
+ return { rows: page.models, total: page.total };
1226
+ };
1227
+ const names = /* @__PURE__ */ new Map();
1228
+ let offset = 0;
1229
+ for (; ; ) {
1230
+ const { rows, total } = await readRows(offset);
1231
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
1232
+ names.set(id, name);
1233
+ }
1234
+ offset += rows.length;
1235
+ if (offset >= total || rows.length === 0) break;
1236
+ }
1237
+ return [...names].map(([id, name]) => ({ id, name })).sort(
1238
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
1239
+ );
1240
+ };
1241
+
1242
+ // src/management/model-catalog-operations/model-catalog-operations.ts
1243
+ var modelCatalogOperations = (call) => ({
1244
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
1245
+ (offset) => call(token, orgId, (client) => {
1246
+ const query = { offset };
1247
+ if (projectId !== void 0)
1248
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
1249
+ params: { path: { project_id: projectId }, query }
1250
+ });
1251
+ if (orgId !== void 0)
1252
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
1253
+ params: { path: { org_id: orgId }, query }
1254
+ });
1255
+ return client.GET("/api/v1/model-catalog", { params: { query } });
1256
+ })
1257
+ )
1258
+ });
1259
+
1260
+ // src/management/list-sdk-projects/list-sdk-projects.ts
1261
+ var listSdkProjects = async (accessToken, organisationId, call) => {
1262
+ if (organisationId.trim().length === 0) {
1263
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
1264
+ statusCode: 400
1265
+ });
1266
+ }
1267
+ const query = {
1268
+ member_user_id: parseManagementSubject(accessToken),
1269
+ org_id: organisationId
1270
+ };
1271
+ const fetchPage = (cursor) => call(
1272
+ accessToken,
1273
+ void 0,
1274
+ (client) => client.GET("/api/v1/projects", {
1275
+ params: {
1276
+ query: cursor === "" ? query : { ...query, cursor }
1277
+ }
1278
+ })
1279
+ ).then((page) => parseCollection(page, parseProject));
1280
+ return drainPages(fetchPage);
1281
+ };
1282
+
1283
+ // src/management/organization-operations/organization-operations.ts
1284
+ var organizationOperations = (call) => ({
1285
+ listOrganizations: async (accessToken) => parseCollection(
1286
+ await call(
1287
+ accessToken,
1288
+ void 0,
1289
+ (client) => client.GET("/api/v1/orgs", {})
1290
+ ),
1291
+ parseOrganization
1292
+ ),
1293
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
1294
+ });
1295
+
1296
+ // src/management/sdk-management-call/sdk-management-call.ts
1297
+ import {
1298
+ createRoute33Client,
1299
+ Route33SdkError
1300
+ } from "@r-33/sdk";
1301
+
1302
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
1303
+ var REFUSED = 422;
1304
+ var REJECTION_MAX_LENGTH = 200;
1305
+ var CONTROL = /\p{Cc}+/gu;
1306
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
1307
+ var OPAQUE_MIN_LENGTH = 20;
1308
+ var rejectionOf = (outcome) => {
1309
+ const body = outcome.error;
1310
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
1311
+ const raw = body["error"];
1312
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
1313
+ return void 0;
1314
+ }
1315
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
1316
+ const lower = sentence.toLowerCase();
1317
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
1318
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
1319
+ );
1320
+ return sentence === "" || secretShaped ? void 0 : sentence;
1321
+ };
1322
+
1323
+ // src/management/sdk-management-call/sdk-management-call.ts
1053
1324
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
1054
1325
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
1055
- var sdkManagementKeys = (options) => {
1326
+ var createSdkCall = (options) => {
1056
1327
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
1057
1328
  const timeoutMs = options.timeoutMs ?? 1e4;
1058
1329
  const fetchImpl = options.fetchImpl;
@@ -1091,14 +1362,18 @@ var sdkManagementKeys = (options) => {
1091
1362
  }
1092
1363
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
1093
1364
  };
1094
- const call = async (accessToken, activeOrgId, run) => {
1365
+ return async (accessToken, activeOrgId, run) => {
1095
1366
  try {
1096
1367
  const outcome = await run(callClient(accessToken, activeOrgId));
1097
1368
  const code = outcome.response?.status;
1098
1369
  if (code === void 0 || code < 200 || code >= 300) {
1370
+ const rejection = rejectionOf(outcome);
1099
1371
  throw new ManagementError(
1100
1372
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
1101
- { statusCode: code }
1373
+ {
1374
+ ...rejection === void 0 ? {} : { rejection },
1375
+ statusCode: code
1376
+ }
1102
1377
  );
1103
1378
  }
1104
1379
  return outcome.data;
@@ -1106,123 +1381,49 @@ var sdkManagementKeys = (options) => {
1106
1381
  throw mapFailure(cause);
1107
1382
  }
1108
1383
  };
1109
- return {
1110
- create: async (accessToken, input) => parseKeyMaterial(
1111
- await call(
1112
- accessToken,
1113
- input.activeOrgId,
1114
- (client) => client.POST("/api/v1/api-keys", {
1115
- body: buildMintRequestBody(input)
1116
- })
1117
- )
1118
- ),
1119
- delete: async (accessToken, id) => {
1120
- await call(
1121
- accessToken,
1122
- void 0,
1123
- (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
1124
- params: { path: { api_key_id: id } }
1125
- })
1126
- );
1127
- },
1128
- get: async (accessToken, id) => parseApiKey(
1129
- await call(
1130
- accessToken,
1131
- void 0,
1132
- (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
1133
- params: { path: { api_key_id: id } }
1134
- })
1135
- )
1136
- ),
1137
- list: async (accessToken) => parseCollection(
1138
- await call(
1139
- accessToken,
1140
- void 0,
1141
- (client) => client.GET("/api/v1/api-keys", {})
1142
- ),
1143
- parseApiKey
1144
- ),
1145
- listOrganizations: async (accessToken) => parseCollection(
1146
- await call(
1147
- accessToken,
1148
- void 0,
1149
- (client) => client.GET("/api/v1/orgs", {})
1150
- ),
1151
- parseOrganization
1152
- ),
1153
- listMemberships: async (accessToken, userId) => parseUserMemberships(
1154
- await call(
1155
- accessToken,
1156
- void 0,
1157
- (client) => client.GET("/api/v1/users/{user_id}/memberships", {
1158
- params: { path: { user_id: userId } }
1159
- })
1160
- )
1161
- ),
1162
- listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
1163
- await call(
1164
- accessToken,
1165
- activeOrgId,
1166
- (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
1167
- params: { path: { user_id: userId } }
1168
- })
1169
- )
1170
- ),
1171
- listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
1172
- await call(
1173
- accessToken,
1174
- activeOrgId,
1175
- (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
1176
- params: { path: { user_id: userId } }
1177
- })
1178
- ),
1179
- parseProjectBudgetState
1180
- ),
1181
- listProjects: async (accessToken, organisationId) => {
1182
- if (organisationId.trim().length === 0) {
1183
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
1184
- statusCode: 400
1185
- });
1186
- }
1187
- const query = {
1188
- member_user_id: parseManagementSubject(accessToken),
1189
- org_id: organisationId
1190
- };
1191
- const fetchPage = (cursor) => call(
1192
- accessToken,
1193
- void 0,
1194
- (client) => client.GET("/api/v1/projects", {
1195
- params: {
1196
- query: cursor === "" ? query : { ...query, cursor }
1197
- }
1198
- })
1199
- ).then((page) => parseCollection(page, parseProject));
1200
- return drainPages(fetchPage);
1201
- },
1202
- regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
1203
- await call(
1204
- accessToken,
1205
- void 0,
1206
- (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
1207
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
1208
- params: { path: { api_key_id: id } }
1209
- })
1210
- )
1211
- ),
1212
- update: async (accessToken, id, input) => parseApiKey(
1213
- await call(
1214
- accessToken,
1215
- void 0,
1216
- (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
1217
- body: {
1218
- budget_currency: "EUR",
1219
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
1220
- ...input.name === void 0 ? {} : { name: input.name }
1221
- },
1222
- params: { path: { api_key_id: id } }
1223
- })
1224
- )
1384
+ };
1385
+
1386
+ // src/management/user-context-operations/user-context-operations.ts
1387
+ var userContextOperations = (call) => ({
1388
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
1389
+ await call(
1390
+ accessToken,
1391
+ void 0,
1392
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
1393
+ params: { path: { user_id: userId } }
1394
+ })
1395
+ )
1396
+ ),
1397
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
1398
+ await call(
1399
+ accessToken,
1400
+ activeOrgId,
1401
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
1402
+ params: { path: { user_id: userId } }
1403
+ })
1225
1404
  )
1405
+ ),
1406
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
1407
+ await call(
1408
+ accessToken,
1409
+ activeOrgId,
1410
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
1411
+ params: { path: { user_id: userId } }
1412
+ })
1413
+ ),
1414
+ parseProjectBudgetState
1415
+ )
1416
+ });
1417
+
1418
+ // src/management/sdk-management-keys/sdk-management-keys.ts
1419
+ var sdkManagementKeys = (options) => {
1420
+ const call = createSdkCall(options);
1421
+ return {
1422
+ ...keyReadOperations(call),
1423
+ ...keyWriteOperations(call),
1424
+ ...modelCatalogOperations(call),
1425
+ ...organizationOperations(call),
1426
+ ...userContextOperations(call)
1226
1427
  };
1227
1428
  };
1228
1429
 
@@ -1233,7 +1434,7 @@ import {
1233
1434
  } from "@r-33/auth-browser";
1234
1435
 
1235
1436
  // src/requested-scopes/requested-scopes.ts
1236
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
1437
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write models:read";
1237
1438
 
1238
1439
  // src/ux/callback-page-copy/callback-page-copy.ts
1239
1440
  var CALLBACK_PAGE_COPY = {