@brazosd/node 0.1.1 → 0.1.3

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.
Files changed (6) hide show
  1. package/README.md +77 -1
  2. package/browser.d.ts +7631 -0
  3. package/browser.js +11233 -0
  4. package/index.d.ts +1133 -68
  5. package/index.js +2069 -114
  6. package/package.json +12 -2
package/index.js CHANGED
@@ -15,14 +15,14 @@ var ApiError = class extends Error {
15
15
  statusText;
16
16
  body;
17
17
  request;
18
- constructor(request2, response, message) {
18
+ constructor(request3, response, message) {
19
19
  super(message);
20
20
  this.name = "ApiError";
21
21
  this.url = response.url;
22
22
  this.status = response.status;
23
23
  this.statusText = response.statusText;
24
24
  this.body = response.body;
25
- this.request = request2;
25
+ this.request = request3;
26
26
  }
27
27
  };
28
28
 
@@ -260,17 +260,17 @@ var getRequestBody = (options) => {
260
260
  };
261
261
  var sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
262
262
  const controller = new AbortController();
263
- const request2 = {
263
+ const request3 = {
264
264
  headers,
265
265
  body: body ?? formData,
266
266
  method: options.method,
267
267
  signal: controller.signal
268
268
  };
269
269
  if (config.WITH_CREDENTIALS) {
270
- request2.credentials = config.CREDENTIALS;
270
+ request3.credentials = config.CREDENTIALS;
271
271
  }
272
272
  onCancel(() => controller.abort());
273
- return await fetch(url, request2);
273
+ return await fetch(url, request3);
274
274
  };
275
275
  var getResponseHeader = (response, responseHeader) => {
276
276
  if (responseHeader) {
@@ -797,6 +797,53 @@ var DefaultService = class {
797
797
  }
798
798
  });
799
799
  }
800
+ /**
801
+ * List the signed-in account's active application grants
802
+ * @returns SSOGrant Active application grants
803
+ * @throws ApiError
804
+ */
805
+ listAccountSsoGrants() {
806
+ return this.httpRequest.request({
807
+ method: "GET",
808
+ url: "/account/sso/grants"
809
+ });
810
+ }
811
+ /**
812
+ * Revoke an application grant using the owning account login
813
+ * @returns void
814
+ * @throws ApiError
815
+ */
816
+ revokeAccountSsoGrant({
817
+ grantId
818
+ }) {
819
+ return this.httpRequest.request({
820
+ method: "DELETE",
821
+ url: "/account/sso/grants/{grantId}",
822
+ path: {
823
+ "grantId": grantId
824
+ }
825
+ });
826
+ }
827
+ /**
828
+ * Authorize using a human account login
829
+ * Uses an account access token, never an application or organization token. The selected org must contain the account; org-user mode additionally requires the application's org. Produces a single-use authorization code, not API credentials.
830
+ * @returns SSOAuthorization Verified callback URL containing code and state
831
+ * @throws ApiError
832
+ */
833
+ authorizeSsoRequest({
834
+ requestId,
835
+ requestBody
836
+ }) {
837
+ return this.httpRequest.request({
838
+ method: "POST",
839
+ url: "/account/sso/requests/{requestId}/authorize",
840
+ path: {
841
+ "requestId": requestId
842
+ },
843
+ body: requestBody,
844
+ mediaType: "application/json"
845
+ });
846
+ }
800
847
  /**
801
848
  * Remove an agent contact list member
802
849
  * Remove a delegation target from the specified agent within the current org
@@ -965,7 +1012,7 @@ var DefaultService = class {
965
1012
  }
966
1013
  /**
967
1014
  * Update agent repository third-party markup
968
- * Organization owners may change the multiplier. Decreases apply immediately. Increases have five days of notice, one day for settlement fanout, and apply on day six.
1015
+ * Enterprise members with repository edit permission, or ordinary-organization owners, may change the multiplier. Decreases apply immediately. Increases have five days of notice, one day for settlement fanout, and apply on day six.
969
1016
  * @returns AgentRepoTrdpMarkupState Third-party markup updated or scheduled
970
1017
  * @throws ApiError
971
1018
  */
@@ -983,7 +1030,7 @@ var DefaultService = class {
983
1030
  mediaType: "application/json",
984
1031
  errors: {
985
1032
  400: `Invalid multiplier or unchanged price`,
986
- 403: `Only an owner of the creator organization may update the price`,
1033
+ 403: `Repository edit permission required in enterprise organizations; creator-organization owner required in ordinary organizations`,
987
1034
  404: `Agent repository not found`,
988
1035
  409: `Another price change is still active`
989
1036
  }
@@ -991,7 +1038,7 @@ var DefaultService = class {
991
1038
  }
992
1039
  /**
993
1040
  * Cancel a pending third-party markup increase
994
- * Organization owners may cancel during the five-day notice window. Settlement and later states are locked.
1041
+ * Enterprise members with repository edit permission, or ordinary-organization owners, may cancel during the five-day notice window. Settlement and later states are locked.
995
1042
  * @returns AgentRepoTrdpMarkupState Increase cancelled
996
1043
  * @throws ApiError
997
1044
  */
@@ -1007,7 +1054,7 @@ var DefaultService = class {
1007
1054
  "changeId": changeId
1008
1055
  },
1009
1056
  errors: {
1010
- 403: `Only an owner of the creator organization may cancel`,
1057
+ 403: `Repository edit permission required in enterprise organizations; creator-organization owner required in ordinary organizations`,
1011
1058
  404: `Repository or change not found`,
1012
1059
  409: `The notice window has ended or the change is no longer cancellable`
1013
1060
  }
@@ -1015,7 +1062,7 @@ var DefaultService = class {
1015
1062
  }
1016
1063
  /**
1017
1064
  * List published agent users' daily token costs
1018
- * Only owners of the publishing organization can query a currently published repository. Includes all deployments and versions, grouped by UTC settlement date and organization-scoped anonymous user UUID. Amounts are actual LLM charges for input, output and cached tokens, including session-title calls; excludes marketplace markup, tools and sandboxes. Agent clone calls belong to the clone's repository. Data is eventually consistent via RisingWave. No consumer organization IDs, numeric user IDs or profile information are returned.
1065
+ * Members with the repository token-costs:read permission (or ordinary-organization owners) can query a currently published repository. Includes all deployments and versions, grouped by UTC settlement date and organization-scoped anonymous user UUID. Amounts are actual LLM charges for input, output and cached tokens, including session-title calls; excludes marketplace markup, tools and sandboxes. Agent clone calls belong to the clone's repository. Data is eventually consistent via RisingWave. No consumer organization IDs, numeric user IDs or profile information are returned.
1019
1066
  * @returns PublishedAgentUserDailyTokenCostPage Daily token costs listed; users without recorded usage have no row.
1020
1067
  * @throws ApiError
1021
1068
  */
@@ -1039,7 +1086,7 @@ var DefaultService = class {
1039
1086
  errors: {
1040
1087
  400: `Invalid days, limit or cursor`,
1041
1088
  401: `Authentication required`,
1042
- 403: `Organization owner permission required`,
1089
+ 403: `Repository token-costs:read permission required in enterprise organizations; owner required in ordinary organizations`,
1043
1090
  404: `Published repository not found in the current organization`
1044
1091
  }
1045
1092
  });
@@ -1189,6 +1236,111 @@ var DefaultService = class {
1189
1236
  }
1190
1237
  });
1191
1238
  }
1239
+ /**
1240
+ * Submit a client-side MCP tool result
1241
+ * First accepted write wins. HTTP 204 confirms storage only; near timeout the model may still receive a timeout. Duplicate submissions and calls not accepting results return 409.
1242
+ * @returns void
1243
+ * @throws ApiError
1244
+ */
1245
+ submitAgentSessionClientMcpResult({
1246
+ sessionId,
1247
+ runId,
1248
+ toolCallId,
1249
+ requestBody
1250
+ }) {
1251
+ return this.httpRequest.request({
1252
+ method: "POST",
1253
+ url: "/agent-sessions/{sessionId}/client-mcp-results/{runId}/{toolCallId}",
1254
+ path: {
1255
+ "sessionId": sessionId,
1256
+ "runId": runId,
1257
+ "toolCallId": toolCallId
1258
+ },
1259
+ body: requestBody,
1260
+ mediaType: "application/json",
1261
+ errors: {
1262
+ 400: `Invalid request`,
1263
+ 403: `Session access denied`,
1264
+ 404: `Session not found`,
1265
+ 409: `Session archived, installation conflict, result already received, or call no longer accepting results`
1266
+ }
1267
+ });
1268
+ }
1269
+ /**
1270
+ * List client-side MCP installations in a session
1271
+ * @returns ClientMCPInstallation Session client-side MCPs
1272
+ * @throws ApiError
1273
+ */
1274
+ listAgentSessionClientMcPs({
1275
+ sessionId
1276
+ }) {
1277
+ return this.httpRequest.request({
1278
+ method: "GET",
1279
+ url: "/agent-sessions/{sessionId}/client-mcps",
1280
+ path: {
1281
+ "sessionId": sessionId
1282
+ },
1283
+ errors: {
1284
+ 400: `Invalid request`,
1285
+ 403: `Session access denied`,
1286
+ 404: `Session not found`,
1287
+ 409: `Session archived, installation conflict, result already received, or call no longer accepting results`
1288
+ }
1289
+ });
1290
+ }
1291
+ /**
1292
+ * Uninstall a session client-side MCP
1293
+ * Idempotent. Uninstall affects future tool dispatch; already waiting calls may still submit their results.
1294
+ * @returns void
1295
+ * @throws ApiError
1296
+ */
1297
+ uninstallAgentSessionClientMcp({
1298
+ sessionId,
1299
+ namespace
1300
+ }) {
1301
+ return this.httpRequest.request({
1302
+ method: "DELETE",
1303
+ url: "/agent-sessions/{sessionId}/client-mcps/{namespace}",
1304
+ path: {
1305
+ "sessionId": sessionId,
1306
+ "namespace": namespace
1307
+ },
1308
+ errors: {
1309
+ 400: `Invalid request`,
1310
+ 403: `Session access denied`,
1311
+ 404: `Session not found`,
1312
+ 409: `Session archived, installation conflict, result already received, or call no longer accepting results`
1313
+ }
1314
+ });
1315
+ }
1316
+ /**
1317
+ * Install or replace a session client-side MCP
1318
+ * Idempotent by session and namespace. Identical definitions retain their revision. Maximum 32 client MCPs per session and 1 MiB per installation.
1319
+ * @returns ClientMCPInstallation Installed snapshot
1320
+ * @throws ApiError
1321
+ */
1322
+ installAgentSessionClientMcp({
1323
+ sessionId,
1324
+ namespace,
1325
+ requestBody
1326
+ }) {
1327
+ return this.httpRequest.request({
1328
+ method: "PUT",
1329
+ url: "/agent-sessions/{sessionId}/client-mcps/{namespace}",
1330
+ path: {
1331
+ "sessionId": sessionId,
1332
+ "namespace": namespace
1333
+ },
1334
+ body: requestBody,
1335
+ mediaType: "application/json",
1336
+ errors: {
1337
+ 400: `Invalid request`,
1338
+ 403: `Session access denied`,
1339
+ 404: `Session not found`,
1340
+ 409: `Session archived, installation conflict, result already received, or call no longer accepting results`
1341
+ }
1342
+ });
1343
+ }
1192
1344
  /**
1193
1345
  * Compact agent session
1194
1346
  * Trigger an asynchronous context compaction run for a managed agent session
@@ -1316,6 +1468,28 @@ var DefaultService = class {
1316
1468
  }
1317
1469
  });
1318
1470
  }
1471
+ /**
1472
+ * Interrupt an agent session and its descendants
1473
+ * Interrupt unarchived working or retrying sessions in the subtree rooted at sessionId, root first and then each level from top to bottom. Children are discovered after their parents are interrupted. Traverse through inactive and archived ancestors. Execution stops on the first error; earlier successful interruptions remain applied and a retry skips them.
1474
+ * @returns AgentSessionTreeActionResult All active sessions interrupted
1475
+ * @throws ApiError
1476
+ */
1477
+ interruptAgentSessionTree({
1478
+ sessionId
1479
+ }) {
1480
+ return this.httpRequest.request({
1481
+ method: "POST",
1482
+ url: "/agent-sessions/{sessionId}/interrupt-tree",
1483
+ path: {
1484
+ "sessionId": sessionId
1485
+ },
1486
+ errors: {
1487
+ 403: `Forbidden`,
1488
+ 404: `Agent session not found`,
1489
+ 409: `A session could not be interrupted; earlier changes remain applied`
1490
+ }
1491
+ });
1492
+ }
1319
1493
  /**
1320
1494
  * Update agent session LLM model
1321
1495
  * Change the model used by subsequent LLM requests in an agent session
@@ -1341,6 +1515,52 @@ var DefaultService = class {
1341
1515
  }
1342
1516
  });
1343
1517
  }
1518
+ /**
1519
+ * Resume an interrupted agent session
1520
+ * Continue unfinished work without adding a user prompt. Starts a new run linked to the stopped run. Already running or otherwise ineligible sessions return 409.
1521
+ * @returns AgentSession Recovery accepted
1522
+ * @throws ApiError
1523
+ */
1524
+ resumeAgentSession({
1525
+ sessionId
1526
+ }) {
1527
+ return this.httpRequest.request({
1528
+ method: "POST",
1529
+ url: "/agent-sessions/{sessionId}/resume",
1530
+ path: {
1531
+ "sessionId": sessionId
1532
+ },
1533
+ errors: {
1534
+ 402: `Payment required`,
1535
+ 403: `Forbidden`,
1536
+ 404: `Agent session not found`,
1537
+ 409: `Session is already running, not resumable, or requires another action`
1538
+ }
1539
+ });
1540
+ }
1541
+ /**
1542
+ * Resume an agent session and its descendants
1543
+ * Resume unarchived interrupted sessions in the subtree rooted at sessionId, deepest level first and root last. Traverse through inactive and archived ancestors. Other session states are skipped. Each resume uses the existing recovery, model, permission and quota checks. Execution stops on the first error; earlier successful resumes remain applied and a retry skips them.
1544
+ * @returns AgentSessionTreeActionResult All eligible sessions resumed
1545
+ * @throws ApiError
1546
+ */
1547
+ resumeAgentSessionTree({
1548
+ sessionId
1549
+ }) {
1550
+ return this.httpRequest.request({
1551
+ method: "POST",
1552
+ url: "/agent-sessions/{sessionId}/resume-tree",
1553
+ path: {
1554
+ "sessionId": sessionId
1555
+ },
1556
+ errors: {
1557
+ 402: `Payment required`,
1558
+ 403: `Forbidden`,
1559
+ 404: `Agent session not found`,
1560
+ 409: `A session could not be resumed; earlier changes remain applied`
1561
+ }
1562
+ });
1563
+ }
1344
1564
  /**
1345
1565
  * Revoke the active agent session share
1346
1566
  * Invalidate the current share link immediately.
@@ -1427,6 +1647,31 @@ var DefaultService = class {
1427
1647
  }
1428
1648
  });
1429
1649
  }
1650
+ /**
1651
+ * Rename agent session
1652
+ * Change the title of a session owned by the current user in the current organization, including archived sessions. A manually set title is preserved when automatic title generation finishes.
1653
+ * @returns AgentSession Agent session renamed
1654
+ * @throws ApiError
1655
+ */
1656
+ updateAgentSessionTitle({
1657
+ sessionId,
1658
+ requestBody
1659
+ }) {
1660
+ return this.httpRequest.request({
1661
+ method: "PUT",
1662
+ url: "/agent-sessions/{sessionId}/title",
1663
+ path: {
1664
+ "sessionId": sessionId
1665
+ },
1666
+ body: requestBody,
1667
+ mediaType: "application/json",
1668
+ errors: {
1669
+ 400: `Title is blank or exceeds 200 characters`,
1670
+ 403: `Forbidden`,
1671
+ 404: `Agent session not found`
1672
+ }
1673
+ });
1674
+ }
1430
1675
  /**
1431
1676
  * Get agent session todo list
1432
1677
  * Get the persisted todo list for a managed agent session ordered by ordinal ascending
@@ -2007,6 +2252,51 @@ var DefaultService = class {
2007
2252
  }
2008
2253
  });
2009
2254
  }
2255
+ /**
2256
+ * Read agent MCP and tool whitelists
2257
+ * @returns AgentToolSettingsResponse Agent tool settings
2258
+ * @throws ApiError
2259
+ */
2260
+ getAgentToolSettings({
2261
+ agentId
2262
+ }) {
2263
+ return this.httpRequest.request({
2264
+ method: "GET",
2265
+ url: "/agents/{agentId}/tool-settings",
2266
+ path: {
2267
+ "agentId": agentId
2268
+ },
2269
+ errors: {
2270
+ 400: `Invalid settings`,
2271
+ 403: `Forbidden`,
2272
+ 404: `Agent not found`
2273
+ }
2274
+ });
2275
+ }
2276
+ /**
2277
+ * Update agent MCP and tool whitelists
2278
+ * @returns AgentToolSettingsResponse Agent tool settings
2279
+ * @throws ApiError
2280
+ */
2281
+ updateAgentToolSettings({
2282
+ agentId,
2283
+ requestBody
2284
+ }) {
2285
+ return this.httpRequest.request({
2286
+ method: "PUT",
2287
+ url: "/agents/{agentId}/tool-settings",
2288
+ path: {
2289
+ "agentId": agentId
2290
+ },
2291
+ body: requestBody,
2292
+ mediaType: "application/json",
2293
+ errors: {
2294
+ 400: `Invalid settings`,
2295
+ 403: `Forbidden`,
2296
+ 404: `Agent not found`
2297
+ }
2298
+ });
2299
+ }
2010
2300
  /**
2011
2301
  * Get recruited agent price confirmation status
2012
2302
  * All members of the consumer organization can read this status for the session price-change banner.
@@ -2030,7 +2320,7 @@ var DefaultService = class {
2030
2320
  }
2031
2321
  /**
2032
2322
  * Confirm a recruited agent price
2033
- * Only an owner of the consumer organization can raise the accepted maximum price and clear a price-caused system pause.
2323
+ * Enterprise members with agent edit permission, or ordinary-organization owners, can raise the accepted maximum price and clear a price-caused system pause.
2034
2324
  * @returns AgentTrdpMarkupStatus Price confirmed
2035
2325
  * @throws ApiError
2036
2326
  */
@@ -2046,7 +2336,7 @@ var DefaultService = class {
2046
2336
  "changeId": changeId
2047
2337
  },
2048
2338
  errors: {
2049
- 403: `Only an owner of the consumer organization may confirm`,
2339
+ 403: `Agent edit permission required in enterprise organizations; consumer-organization owner required in ordinary organizations`,
2050
2340
  404: `Agent or relevant price change not found`,
2051
2341
  409: `The change is cancelled, failed, stale, or otherwise not confirmable`
2052
2342
  }
@@ -3240,7 +3530,7 @@ var DefaultService = class {
3240
3530
  }
3241
3531
  /**
3242
3532
  * Upload cloud drive file
3243
- * Upload a file into a canonical cloud drive destination path. Query parameters are signed; the multipart body is sent with unsigned payload mode and the file content integrity is checked with the signed sha256 query parameter.
3533
+ * Stream a file of at most 5 GiB (5368709120 bytes) into a canonical cloud drive destination path without buffering the complete payload in application memory or on disk. Query parameters are signed; the multipart body is sent with unsigned payload mode and the file content integrity is checked with the signed sha256 query parameter. Interrupted uploads must be restarted from the beginning.
3244
3534
  * @returns CloudDriveFnode File uploaded
3245
3535
  * @throws ApiError
3246
3536
  */
@@ -3273,6 +3563,7 @@ var DefaultService = class {
3273
3563
  404: `Parent directory not found`,
3274
3564
  409: `File already exists or flags conflict`,
3275
3565
  412: `Existing file content no longer matches If-Match`,
3566
+ 413: `File exceeds the 5 GiB limit`,
3276
3567
  429: `This client already wrote the same file within the last second`,
3277
3568
  503: `File-write rate limiter unavailable`
3278
3569
  }
@@ -3280,7 +3571,7 @@ var DefaultService = class {
3280
3571
  }
3281
3572
  /**
3282
3573
  * Upload cloud drive file into user tmp
3283
- * Stream a file of at most 512 MiB into the authenticated user's cloud-drive temporary area without buffering the complete payload in application memory or on disk. The backend allocates a unique dated tmp path so clients do not need to generate one. Interrupted uploads must be restarted from the beginning.
3574
+ * Stream a file of at most 5 GiB (5368709120 bytes) into the authenticated user's cloud-drive temporary area without buffering the complete payload in application memory or on disk. The backend allocates a unique dated tmp path so clients do not need to generate one. Interrupted uploads must be restarted from the beginning.
3284
3575
  * @returns CloudDriveFnode File uploaded into tmp
3285
3576
  * @throws ApiError
3286
3577
  */
@@ -3301,7 +3592,7 @@ var DefaultService = class {
3301
3592
  402: `Payment required`,
3302
3593
  403: `Forbidden`,
3303
3594
  409: `Tmp path conflict`,
3304
- 413: `File exceeds the 512 MiB limit`
3595
+ 413: `File exceeds the 5 GiB limit`
3305
3596
  }
3306
3597
  });
3307
3598
  }
@@ -3312,6 +3603,7 @@ var DefaultService = class {
3312
3603
  * @throws ApiError
3313
3604
  */
3314
3605
  listConsentForms({
3606
+ pendingOnly,
3315
3607
  offset,
3316
3608
  limit
3317
3609
  }) {
@@ -3319,6 +3611,7 @@ var DefaultService = class {
3319
3611
  method: "GET",
3320
3612
  url: "/consent-forms",
3321
3613
  query: {
3614
+ "pendingOnly": pendingOnly,
3322
3615
  "offset": offset,
3323
3616
  "limit": limit
3324
3617
  },
@@ -3696,7 +3989,7 @@ var DefaultService = class {
3696
3989
  }
3697
3990
  /**
3698
3991
  * Register device
3699
- * Register a new device. Organization settings may disable registration for members; the organization owner is exempt. Existing device connections and usage are unchanged.
3992
+ * Register a new device. Enterprise organizations require devices:create. Ordinary organization settings may disable registration for members; the organization owner is exempt. Existing device connections and usage are unchanged.
3700
3993
  * @returns RegisterDeviceResult Device registered
3701
3994
  * @throws ApiError
3702
3995
  */
@@ -3885,6 +4178,33 @@ var DefaultService = class {
3885
4178
  }
3886
4179
  });
3887
4180
  }
4181
+ /**
4182
+ * Set device access scope
4183
+ * Set a device to organization-visible or private. In non-enterprise organizations only the device owner can change its scope. Enterprise organizations use the existing device access permission, subject to device visibility; ownership does not bypass enterprise permissions. Setting orgScope to false saves private visibility before requesting disconnection of the current device tunnel. Repeating a private request retries disconnection. Device credentials remain valid for reconnecting.
4184
+ * @returns Device Device access scope updated and, for private scope, tunnel disconnection requested if a tunnel record exists. This does not acknowledge actual closure.
4185
+ * @throws ApiError
4186
+ */
4187
+ setDeviceScope({
4188
+ deviceId,
4189
+ requestBody
4190
+ }) {
4191
+ return this.httpRequest.request({
4192
+ method: "PUT",
4193
+ url: "/devices/{deviceId}/scope",
4194
+ path: {
4195
+ "deviceId": deviceId
4196
+ },
4197
+ body: requestBody,
4198
+ mediaType: "application/json",
4199
+ errors: {
4200
+ 400: `A boolean orgScope is required`,
4201
+ 401: `Unauthorized`,
4202
+ 403: `Device ownership or enterprise device permission required`,
4203
+ 404: `Device not found or not visible to the current user`,
4204
+ 503: `Scope was saved as private, but tunnel lookup or disconnect notification failed. The device remains private; its owner can retry the request.`
4205
+ }
4206
+ });
4207
+ }
3888
4208
  /**
3889
4209
  * Rotate device token
3890
4210
  * @returns RotateDeviceTokenResult Device token rotated
@@ -4162,7 +4482,7 @@ var DefaultService = class {
4162
4482
  }
4163
4483
  /**
4164
4484
  * Update current organization
4165
- * Update the current organization's profile. Only the organization owner can update it.
4485
+ * Update the current organization's profile. An authorized enterprise member or an ordinary-organization owner can update it.
4166
4486
  * @returns AccountOrg Current organization updated
4167
4487
  * @throws ApiError
4168
4488
  */
@@ -4176,7 +4496,7 @@ var DefaultService = class {
4176
4496
  mediaType: "application/json",
4177
4497
  errors: {
4178
4498
  400: `Organization name is required`,
4179
- 403: `Only the organization owner can update the organization`,
4499
+ 403: `An authorized enterprise member or an ordinary-organization owner can update the organization`,
4180
4500
  404: `Current organization user not found`
4181
4501
  }
4182
4502
  });
@@ -4346,7 +4666,7 @@ var DefaultService = class {
4346
4666
  }
4347
4667
  /**
4348
4668
  * Get org invitation token
4349
- * Get the current organization invitation token. Only the org owner can read it.
4669
+ * Get the current organization invitation token. An authorized enterprise member or an ordinary-organization owner can read it.
4350
4670
  * @returns OrgInvitationToken Token exists
4351
4671
  * @throws ApiError
4352
4672
  */
@@ -4355,7 +4675,7 @@ var DefaultService = class {
4355
4675
  method: "GET",
4356
4676
  url: "/org-invitation-token",
4357
4677
  errors: {
4358
- 403: `Only the org owner can read invitation tokens`,
4678
+ 403: `An authorized enterprise member or an ordinary-organization owner can read invitation tokens`,
4359
4679
  404: `No invitation token exists`
4360
4680
  }
4361
4681
  });
@@ -4376,7 +4696,7 @@ var DefaultService = class {
4376
4696
  mediaType: "application/json",
4377
4697
  errors: {
4378
4698
  400: `Invalid request`,
4379
- 403: `Only the org owner can manage invitation tokens`
4699
+ 403: `An authorized enterprise member or an ordinary-organization owner can manage invitation tokens`
4380
4700
  }
4381
4701
  });
4382
4702
  }
@@ -4391,7 +4711,7 @@ var DefaultService = class {
4391
4711
  method: "POST",
4392
4712
  url: "/org-invitation-token/refresh",
4393
4713
  errors: {
4394
- 403: `Only the org owner can manage invitation tokens`,
4714
+ 403: `An authorized enterprise member or an ordinary-organization owner can manage invitation tokens`,
4395
4715
  404: `No invitation token exists`
4396
4716
  }
4397
4717
  });
@@ -4463,7 +4783,7 @@ var DefaultService = class {
4463
4783
  }
4464
4784
  /**
4465
4785
  * Create an organization-managed account
4466
- * Only the current organization's owner may provision an account while its enterprise subscription is active. Enterprise credentials also require rn:orgs:<orgId>:users:create; ownership does not bypass RN checks. Creates an account without a phone number, allocates an enterprise seat, and returns a random temporary password once. The user must change it on first login. Never log the response.
4786
+ * Requires rn:orgs:<orgId>:users:create in an enterprise organization with an active subscription. Ordinary organizations retain the owner fallback, but still require an active subscription to provision accounts. Creates an account without a phone number, allocates an enterprise seat, and returns a random temporary password once. The user must change it on first login. Never log the response.
4467
4787
  * @returns ManagedAccountCredentials Account created; save the temporary password before leaving this response
4468
4788
  * @throws ApiError
4469
4789
  */
@@ -4479,7 +4799,7 @@ var DefaultService = class {
4479
4799
  400: `Username or display name is empty`,
4480
4800
  401: `Organization authentication required`,
4481
4801
  402: `Insufficient credits for an additional enterprise seat`,
4482
- 403: `Organization owner, active enterprise subscription, and enterprise RN permission required`,
4802
+ 403: `Active enterprise subscription and the operation RN permission required`,
4483
4803
  404: `Organization not found`,
4484
4804
  409: `Username is already taken (plain text), or organization active-user quota exceeded (JSON)`
4485
4805
  }
@@ -4487,7 +4807,7 @@ var DefaultService = class {
4487
4807
  }
4488
4808
  /**
4489
4809
  * Deactivate org user
4490
- * Deactivate an existing org user. Only the org owner can deactivate users.
4810
+ * Deactivate an existing org user. An authorized enterprise member or an ordinary-organization owner can deactivate users.
4491
4811
  * @returns void
4492
4812
  * @throws ApiError
4493
4813
  */
@@ -4501,7 +4821,7 @@ var DefaultService = class {
4501
4821
  "userId": userId
4502
4822
  },
4503
4823
  errors: {
4504
- 403: `Only the org owner can delete users`,
4824
+ 403: `An authorized enterprise member or an ordinary-organization owner can delete users`,
4505
4825
  404: `Org user not found`,
4506
4826
  409: `The organization owner cannot be deactivated`
4507
4827
  }
@@ -4525,14 +4845,14 @@ var DefaultService = class {
4525
4845
  body: requestBody,
4526
4846
  mediaType: "application/json",
4527
4847
  errors: {
4528
- 403: `Organization owner required`,
4848
+ 403: `Operation RN permission required for enterprise organizations; owner required for ordinary organizations`,
4529
4849
  404: `Managed member not found in this organization`
4530
4850
  }
4531
4851
  });
4532
4852
  }
4533
4853
  /**
4534
4854
  * Deactivate a managed account
4535
- * Owner only. Stops login, revokes credentials and releases its occupied seat. Repeated deactivation preserves the original cooldown start.
4855
+ * Requires the operation RN in enterprise organizations; ordinary organizations require the owner. Stops login, revokes credentials and releases its occupied seat. Repeated deactivation preserves the original cooldown start.
4536
4856
  * @returns void
4537
4857
  * @throws ApiError
4538
4858
  */
@@ -4546,7 +4866,7 @@ var DefaultService = class {
4546
4866
  "userId": userId
4547
4867
  },
4548
4868
  errors: {
4549
- 403: `Organization owner required`,
4869
+ 403: `Operation RN permission required for enterprise organizations; owner required for ordinary organizations`,
4550
4870
  404: `Managed member not found`,
4551
4871
  409: `Organization owner cannot be deactivated`
4552
4872
  }
@@ -4554,7 +4874,7 @@ var DefaultService = class {
4554
4874
  }
4555
4875
  /**
4556
4876
  * Reactivate a managed account
4557
- * Owner only, at least 24 hours after deactivation. Rechecks quotas and enterprise seats transactionally. Does not reset the password or automatically log in the user.
4877
+ * Requires the operation RN in enterprise organizations, or the owner in ordinary organizations, at least 24 hours after deactivation. Rechecks quotas and enterprise seats transactionally. Does not reset the password or automatically log in the user.
4558
4878
  * @returns void
4559
4879
  * @throws ApiError
4560
4880
  */
@@ -4569,7 +4889,7 @@ var DefaultService = class {
4569
4889
  },
4570
4890
  errors: {
4571
4891
  402: `Insufficient credits for an additional seat`,
4572
- 403: `Organization owner required`,
4892
+ 403: `Operation RN permission required for enterprise organizations; owner required for ordinary organizations`,
4573
4893
  404: `Managed member not found`,
4574
4894
  409: `Cooldown has not elapsed or a member quota is exceeded`
4575
4895
  }
@@ -4577,7 +4897,7 @@ var DefaultService = class {
4577
4897
  }
4578
4898
  /**
4579
4899
  * Reset a managed account's password
4580
- * Owner only. Generates a temporary password and revokes existing credentials without changing activation status.
4900
+ * Requires the operation RN in enterprise organizations; ordinary organizations require the owner. Generates a temporary password and revokes existing credentials without changing activation status.
4581
4901
  * @returns ManagedPasswordReset Temporary password generated
4582
4902
  * @throws ApiError
4583
4903
  */
@@ -4591,7 +4911,7 @@ var DefaultService = class {
4591
4911
  "userId": userId
4592
4912
  },
4593
4913
  errors: {
4594
- 403: `Organization owner required`,
4914
+ 403: `Operation RN permission required for enterprise organizations; owner required for ordinary organizations`,
4595
4915
  404: `Managed member not found`
4596
4916
  }
4597
4917
  });
@@ -4640,7 +4960,7 @@ var DefaultService = class {
4640
4960
  }
4641
4961
  /**
4642
4962
  * Get organization agent-session settings
4643
- * Get the current organization's inactivity archive timeout. Only the organization owner can read this setting.
4963
+ * Get the current organization's inactivity archive timeout. An authorized enterprise member or an ordinary-organization owner can read this setting.
4644
4964
  * @returns OrgAgentSessionSettings Agent-session settings returned
4645
4965
  * @throws ApiError
4646
4966
  */
@@ -4649,13 +4969,13 @@ var DefaultService = class {
4649
4969
  method: "GET",
4650
4970
  url: "/org/agent-session-settings",
4651
4971
  errors: {
4652
- 403: `Only the organization owner can read these settings`
4972
+ 403: `An authorized enterprise member or an ordinary-organization owner can read these settings`
4653
4973
  }
4654
4974
  });
4655
4975
  }
4656
4976
  /**
4657
4977
  * Update organization agent-session settings
4658
- * Set the inactivity archive timeout for all sessions in the current organization. Only the organization owner can update this setting.
4978
+ * Set the inactivity archive timeout for all sessions in the current organization. An authorized enterprise member or an ordinary-organization owner can update this setting.
4659
4979
  * @returns OrgAgentSessionSettings Agent-session settings updated
4660
4980
  * @throws ApiError
4661
4981
  */
@@ -4669,7 +4989,7 @@ var DefaultService = class {
4669
4989
  mediaType: "application/json",
4670
4990
  errors: {
4671
4991
  400: `Timeout must be between 1 and 288 hours`,
4672
- 403: `Only the organization owner can update these settings`
4992
+ 403: `An authorized enterprise member or an ordinary-organization owner can update these settings`
4673
4993
  }
4674
4994
  });
4675
4995
  }
@@ -4689,7 +5009,7 @@ var DefaultService = class {
4689
5009
  mediaType: "multipart/form-data",
4690
5010
  errors: {
4691
5011
  400: `Invalid request`,
4692
- 403: `Only the organization owner can update the organization avatar`,
5012
+ 403: `An authorized enterprise member or an ordinary-organization owner can update the organization avatar`,
4693
5013
  404: `Org user not found`
4694
5014
  }
4695
5015
  });
@@ -4711,7 +5031,7 @@ var DefaultService = class {
4711
5031
  }
4712
5032
  /**
4713
5033
  * Activate organization enterprise subscription
4714
- * Activate enterprise billing, or restore automatic renewal for an active paid period. Only the organization owner can perform this operation.
5034
+ * Activate enterprise billing, or restore automatic renewal for an active paid period. An authorized enterprise member or an ordinary-organization owner can perform this operation.
4715
5035
  * @returns OrgEnterpriseSubscription Enterprise subscription activated or automatic renewal restored
4716
5036
  * @throws ApiError
4717
5037
  */
@@ -4721,7 +5041,7 @@ var DefaultService = class {
4721
5041
  url: "/org/enterprise",
4722
5042
  errors: {
4723
5043
  402: `Organization credits are insufficient for the initial seat charge`,
4724
- 403: `Only the organization owner can activate enterprise billing`
5044
+ 403: `An authorized enterprise member or an ordinary-organization owner can activate enterprise billing`
4725
5045
  }
4726
5046
  });
4727
5047
  }
@@ -4839,7 +5159,7 @@ var DefaultService = class {
4839
5159
  }
4840
5160
  /**
4841
5161
  * Cancel organization enterprise renewal
4842
- * Stop automatic renewal after the current paid period. The organization remains enterprise until the period ends. Only the organization owner can perform this operation.
5162
+ * Stop automatic renewal after the current paid period. The organization remains enterprise until the period ends. An authorized enterprise member or an ordinary-organization owner can perform this operation.
4843
5163
  * @returns OrgEnterpriseSubscription Automatic renewal cancelled
4844
5164
  * @throws ApiError
4845
5165
  */
@@ -4848,13 +5168,13 @@ var DefaultService = class {
4848
5168
  method: "POST",
4849
5169
  url: "/org/enterprise/cancel-renewal",
4850
5170
  errors: {
4851
- 403: `Only the organization owner can cancel enterprise renewal`
5171
+ 403: `An authorized enterprise member or an ordinary-organization owner can cancel enterprise renewal`
4852
5172
  }
4853
5173
  });
4854
5174
  }
4855
5175
  /**
4856
5176
  * Get organization feature settings
4857
- * Read organization settings and the current user's effective permissions. All settings default to allowed. Owners bypass recruitment and device registration restrictions only.
5177
+ * Read organization settings and the current user's effective permissions. All settings default to allowed. Enterprise recruitment and device registration use RN permissions instead of the legacy member switches; ordinary-organization owners bypass those two switches. Publishing and sharing switches apply to everyone.
4858
5178
  * @returns OrgFeatureSettingsResponse Organization feature settings and effective permissions
4859
5179
  * @throws ApiError
4860
5180
  */
@@ -4869,7 +5189,7 @@ var DefaultService = class {
4869
5189
  }
4870
5190
  /**
4871
5191
  * Update organization feature settings
4872
- * Owner only. Replace all four settings. Restrictions apply to subsequent recruitment, device registration, publishing, and share creation or rotation requests. Existing agents, devices, publications, and shares remain unchanged.
5192
+ * Requires the operation RN in enterprise organizations; ordinary organizations require the owner. Replace all four settings. Restrictions apply to subsequent recruitment, device registration, publishing, and share creation or rotation requests. Existing agents, devices, publications, and shares remain unchanged.
4873
5193
  * @returns OrgFeatureSettingsResponse Organization feature settings updated
4874
5194
  * @throws ApiError
4875
5195
  */
@@ -4884,7 +5204,7 @@ var DefaultService = class {
4884
5204
  errors: {
4885
5205
  400: `All four boolean settings are required`,
4886
5206
  401: `Unauthorized`,
4887
- 403: `Organization owner required`
5207
+ 403: `Operation RN permission required for enterprise organizations; owner required for ordinary organizations`
4888
5208
  }
4889
5209
  });
4890
5210
  }
@@ -5107,7 +5427,7 @@ var DefaultService = class {
5107
5427
  }
5108
5428
  /**
5109
5429
  * Replace organization model settings
5110
- * Only the organization owner may change these settings. Omitted or null overrides restore the corresponding default. Existing agents, sessions, and forks are not migrated.
5430
+ * Enterprise members with llm-model-settings:edit, or ordinary-organization owners, may change these settings. Omitted or null overrides restore the corresponding default. Existing agents, sessions, and forks are not migrated.
5111
5431
  * @returns OrgLlmSettings Organization model settings saved
5112
5432
  * @throws ApiError
5113
5433
  */
@@ -5121,11 +5441,26 @@ var DefaultService = class {
5121
5441
  mediaType: "application/json",
5122
5442
  errors: {
5123
5443
  400: `Invalid settings or model capability`,
5124
- 403: `Owner permission or an active Enterprise subscription for a custom model is required`,
5444
+ 403: `Management permission or an active Enterprise subscription for a custom model is required`,
5125
5445
  404: `Model not found`
5126
5446
  }
5127
5447
  });
5128
5448
  }
5449
+ /**
5450
+ * Get the current user's organization authorization
5451
+ * Returns the authenticated user's effective enterprise rules, including group and policy grants and denies, or ordinary-organization owner fallback. Subscription expiry does not disable enterprise authorization. This read-only response never initializes grants and cannot inspect another user. Operations always recheck authorization independently.
5452
+ * @returns CurrentOrgPermissions Current organization authorization
5453
+ * @throws ApiError
5454
+ */
5455
+ getCurrentOrgPermissions() {
5456
+ return this.httpRequest.request({
5457
+ method: "GET",
5458
+ url: "/org/permissions",
5459
+ errors: {
5460
+ 401: `Authentication required`
5461
+ }
5462
+ });
5463
+ }
5129
5464
  /**
5130
5465
  * List organization quotas
5131
5466
  * List effective quota limits and current usage for the authenticated organization.
@@ -5142,60 +5477,106 @@ var DefaultService = class {
5142
5477
  });
5143
5478
  }
5144
5479
  /**
5145
- * Get a member's bound policy IDs
5146
- * Requires an enterprise organization and the corresponding enterprise RN permission.
5147
- * @returns EnterprisePermissionPolicyBindings Get a member's bound policy IDs
5480
+ * Get an enterprise member's daily usage budget
5481
+ * Uses the current UTC billing date and all usage categories from the billing aggregates. Only Agent/model admission is limited. Subscription expiry does not remove configured budgets.
5482
+ * @returns UserDailyBudget Current budget and aggregated usage
5148
5483
  * @throws ApiError
5149
5484
  */
5150
- getUserEnterprisePermissionPolicies({
5485
+ getUserDailyBudget({
5151
5486
  userId
5152
5487
  }) {
5153
5488
  return this.httpRequest.request({
5154
5489
  method: "GET",
5155
- url: "/org/users/{userId}/enterprise-permission-policies",
5490
+ url: "/org/users/{userId}/daily-budget",
5156
5491
  path: {
5157
5492
  "userId": userId
5158
5493
  },
5159
5494
  errors: {
5160
- 400: `Invalid input`,
5161
- 403: `Permission denied`,
5162
- 404: `Policy or member not found in this organization`,
5163
- 409: `Policy name already exists`
5495
+ 403: `Enterprise organization and member budget read permission required`,
5496
+ 404: `Member not found in this organization`
5164
5497
  }
5165
5498
  });
5166
5499
  }
5167
5500
  /**
5168
- * Replace a member's policy bindings
5169
- * Requires an enterprise organization and the corresponding enterprise RN permission. Atomically replaces all bindings without changing direct user rules. Empty policyIds detaches every policy. Subsequent login or renewal does not restore detached policies.
5170
- * @returns EnterprisePermissionPolicyBindings Replace a member's policy bindings
5501
+ * Set an enterprise member's daily usage budget
5502
+ * Zero blocks new Agent/model work; omit limitMicroyuans or set it to null for unlimited usage. Settings propagate to other workers within 7 seconds while dependencies are healthy. Usage checks additionally cache billing aggregates for at most 5 seconds. RisingWave lag and already admitted concurrent calls can cause overspending. No automatic replay of stopped work occurs at the next UTC day.
5503
+ * @returns UserDailyBudget Saved budget and current aggregated usage
5171
5504
  * @throws ApiError
5172
5505
  */
5173
- replaceUserEnterprisePermissionPolicies({
5506
+ setUserDailyBudget({
5174
5507
  userId,
5175
5508
  requestBody
5176
5509
  }) {
5177
5510
  return this.httpRequest.request({
5178
5511
  method: "PUT",
5179
- url: "/org/users/{userId}/enterprise-permission-policies",
5512
+ url: "/org/users/{userId}/daily-budget",
5180
5513
  path: {
5181
5514
  "userId": userId
5182
5515
  },
5183
5516
  body: requestBody,
5184
5517
  mediaType: "application/json",
5185
5518
  errors: {
5186
- 400: `Invalid input`,
5187
- 403: `Permission denied`,
5188
- 404: `Policy or member not found in this organization`,
5189
- 409: `Policy name already exists`
5519
+ 400: `Invalid amount`,
5520
+ 403: `Enterprise organization and member budget edit permission required`,
5521
+ 404: `Member not found in this organization`
5190
5522
  }
5191
5523
  });
5192
5524
  }
5193
5525
  /**
5194
- * Get a member's enterprise permission rules
5195
- * Requires the corresponding enterprise RN permission. Returns direct user rules only; bound policy rules are evaluated separately. Existing resource access checks still apply.
5196
- * @returns EnterprisePermissionRules Current rules
5197
- * @throws ApiError
5198
- */
5526
+ * Get a member's bound policy IDs
5527
+ * Requires an enterprise organization and the corresponding enterprise RN permission.
5528
+ * @returns EnterprisePermissionPolicyBindings Get a member's bound policy IDs
5529
+ * @throws ApiError
5530
+ */
5531
+ getUserEnterprisePermissionPolicies({
5532
+ userId
5533
+ }) {
5534
+ return this.httpRequest.request({
5535
+ method: "GET",
5536
+ url: "/org/users/{userId}/enterprise-permission-policies",
5537
+ path: {
5538
+ "userId": userId
5539
+ },
5540
+ errors: {
5541
+ 400: `Invalid input`,
5542
+ 403: `Permission denied`,
5543
+ 404: `Policy or member not found in this organization`,
5544
+ 409: `Policy name already exists`
5545
+ }
5546
+ });
5547
+ }
5548
+ /**
5549
+ * Replace a member's policy bindings
5550
+ * Requires an enterprise organization and the corresponding enterprise RN permission. Atomically replaces all bindings without changing direct user rules. Empty policyIds detaches every policy. Subsequent login or renewal does not restore detached policies.
5551
+ * @returns EnterprisePermissionPolicyBindings Replace a member's policy bindings
5552
+ * @throws ApiError
5553
+ */
5554
+ replaceUserEnterprisePermissionPolicies({
5555
+ userId,
5556
+ requestBody
5557
+ }) {
5558
+ return this.httpRequest.request({
5559
+ method: "PUT",
5560
+ url: "/org/users/{userId}/enterprise-permission-policies",
5561
+ path: {
5562
+ "userId": userId
5563
+ },
5564
+ body: requestBody,
5565
+ mediaType: "application/json",
5566
+ errors: {
5567
+ 400: `Invalid input`,
5568
+ 403: `Permission denied`,
5569
+ 404: `Policy or member not found in this organization`,
5570
+ 409: `Policy name already exists`
5571
+ }
5572
+ });
5573
+ }
5574
+ /**
5575
+ * Get a member's enterprise permission rules
5576
+ * Requires the corresponding enterprise RN permission. Returns direct user rules only; bound policy rules are evaluated separately. Existing resource access checks still apply.
5577
+ * @returns EnterprisePermissionRules Current rules
5578
+ * @throws ApiError
5579
+ */
5199
5580
  getUserEnterprisePermissions({
5200
5581
  userId
5201
5582
  }) {
@@ -5285,7 +5666,7 @@ var DefaultService = class {
5285
5666
  q,
5286
5667
  limit,
5287
5668
  page = 1,
5288
- pageSize = 24
5669
+ pageSize: pageSize2 = 24
5289
5670
  }) {
5290
5671
  return this.httpRequest.request({
5291
5672
  method: "GET",
@@ -5294,7 +5675,7 @@ var DefaultService = class {
5294
5675
  "q": q,
5295
5676
  "limit": limit,
5296
5677
  "page": page,
5297
- "pageSize": pageSize
5678
+ "pageSize": pageSize2
5298
5679
  },
5299
5680
  errors: {
5300
5681
  400: `Invalid page or page size`
@@ -5340,6 +5721,43 @@ var DefaultService = class {
5340
5721
  }
5341
5722
  });
5342
5723
  }
5724
+ /**
5725
+ * List public snapshots
5726
+ * @returns PublicSnapshot Public snapshots
5727
+ * @throws ApiError
5728
+ */
5729
+ listPublicSnapshots({
5730
+ after
5731
+ }) {
5732
+ return this.httpRequest.request({
5733
+ method: "GET",
5734
+ url: "/public-snapshots",
5735
+ query: {
5736
+ "after": after
5737
+ }
5738
+ });
5739
+ }
5740
+ /**
5741
+ * Import a public snapshot into the current organization
5742
+ * Create an independent saved snapshot reference to the same immutable resource. Storage billing starts when imported.
5743
+ * @returns Snapshot Organization snapshot created
5744
+ * @throws ApiError
5745
+ */
5746
+ importPublicSnapshot({
5747
+ publicationId
5748
+ }) {
5749
+ return this.httpRequest.request({
5750
+ method: "POST",
5751
+ url: "/public-snapshots/{publicationID}/copies",
5752
+ path: {
5753
+ "publicationID": publicationId
5754
+ },
5755
+ errors: {
5756
+ 402: `Payment required`,
5757
+ 404: `Public snapshot not found`
5758
+ }
5759
+ });
5760
+ }
5343
5761
  /**
5344
5762
  * Get public agent
5345
5763
  * Get the current published main version of a public agent repository. This endpoint does not require authentication.
@@ -5426,7 +5844,7 @@ var DefaultService = class {
5426
5844
  }
5427
5845
  /**
5428
5846
  * Reserve or change the org's publisher namespace
5429
- * Only the organization owner can change the namespace. It can be changed once every 7 days; prior namespaces remain reserved and working for 60 days.
5847
+ * An authorized enterprise member or an ordinary-organization owner can change the namespace. It can be changed once every 7 days; prior namespaces remain reserved and working for 60 days.
5430
5848
  * @returns PublisherNamespace Namespace updated
5431
5849
  * @throws ApiError
5432
5850
  */
@@ -5440,7 +5858,7 @@ var DefaultService = class {
5440
5858
  mediaType: "application/json",
5441
5859
  errors: {
5442
5860
  400: `Invalid namespace`,
5443
- 403: `Only the organization owner can change the namespace`,
5861
+ 403: `An authorized enterprise member or an ordinary-organization owner can change the namespace`,
5444
5862
  409: `Namespace is already reserved`,
5445
5863
  429: `Namespace was changed within the last 7 days`
5446
5864
  }
@@ -5543,6 +5961,154 @@ var DefaultService = class {
5543
5961
  }
5544
5962
  });
5545
5963
  }
5964
+ /**
5965
+ * List accessible platform scheduled tasks in the current organization
5966
+ * @returns ScheduledTask Organization tasks and the current user's personal tasks
5967
+ * @throws ApiError
5968
+ */
5969
+ listScheduledTasks({
5970
+ scope
5971
+ }) {
5972
+ return this.httpRequest.request({
5973
+ method: "GET",
5974
+ url: "/scheduled-tasks",
5975
+ query: {
5976
+ "scope": scope
5977
+ }
5978
+ });
5979
+ }
5980
+ /**
5981
+ * Create a platform scheduled task
5982
+ * @returns ScheduledTask Created
5983
+ * @throws ApiError
5984
+ */
5985
+ createScheduledTask({
5986
+ requestBody
5987
+ }) {
5988
+ return this.httpRequest.request({
5989
+ method: "POST",
5990
+ url: "/scheduled-tasks",
5991
+ body: requestBody,
5992
+ mediaType: "application/json",
5993
+ errors: {
5994
+ 400: `Invalid task or request body exceeds 64 KiB`,
5995
+ 403: `Permission denied`,
5996
+ 409: `Organization quota exceeded`
5997
+ }
5998
+ });
5999
+ }
6000
+ /**
6001
+ * Delete a task while retaining its history
6002
+ * @returns void
6003
+ * @throws ApiError
6004
+ */
6005
+ deleteScheduledTask({
6006
+ scheduledTaskId
6007
+ }) {
6008
+ return this.httpRequest.request({
6009
+ method: "DELETE",
6010
+ url: "/scheduled-tasks/{scheduledTaskId}",
6011
+ path: {
6012
+ "scheduledTaskId": scheduledTaskId
6013
+ }
6014
+ });
6015
+ }
6016
+ /**
6017
+ * Get a scheduled task
6018
+ * @returns ScheduledTask Task
6019
+ * @throws ApiError
6020
+ */
6021
+ getScheduledTask({
6022
+ scheduledTaskId
6023
+ }) {
6024
+ return this.httpRequest.request({
6025
+ method: "GET",
6026
+ url: "/scheduled-tasks/{scheduledTaskId}",
6027
+ path: {
6028
+ "scheduledTaskId": scheduledTaskId
6029
+ },
6030
+ errors: {
6031
+ 404: `Task not found`
6032
+ }
6033
+ });
6034
+ }
6035
+ /**
6036
+ * Update a task without changing its owner or execution user
6037
+ * @returns ScheduledTask Updated
6038
+ * @throws ApiError
6039
+ */
6040
+ updateScheduledTask({
6041
+ scheduledTaskId,
6042
+ requestBody
6043
+ }) {
6044
+ return this.httpRequest.request({
6045
+ method: "PUT",
6046
+ url: "/scheduled-tasks/{scheduledTaskId}",
6047
+ path: {
6048
+ "scheduledTaskId": scheduledTaskId
6049
+ },
6050
+ body: requestBody,
6051
+ mediaType: "application/json",
6052
+ errors: {
6053
+ 400: `Invalid task`,
6054
+ 409: `Task is running or already completed`
6055
+ }
6056
+ });
6057
+ }
6058
+ /**
6059
+ * Pause a scheduled task
6060
+ * @returns ScheduledTask Paused
6061
+ * @throws ApiError
6062
+ */
6063
+ pauseScheduledTask({
6064
+ scheduledTaskId
6065
+ }) {
6066
+ return this.httpRequest.request({
6067
+ method: "POST",
6068
+ url: "/scheduled-tasks/{scheduledTaskId}/pause",
6069
+ path: {
6070
+ "scheduledTaskId": scheduledTaskId
6071
+ },
6072
+ errors: {
6073
+ 409: `Task cannot be paused`
6074
+ }
6075
+ });
6076
+ }
6077
+ /**
6078
+ * Resume a scheduled task
6079
+ * @returns ScheduledTask Resumed
6080
+ * @throws ApiError
6081
+ */
6082
+ resumeScheduledTask({
6083
+ scheduledTaskId
6084
+ }) {
6085
+ return this.httpRequest.request({
6086
+ method: "POST",
6087
+ url: "/scheduled-tasks/{scheduledTaskId}/resume",
6088
+ path: {
6089
+ "scheduledTaskId": scheduledTaskId
6090
+ },
6091
+ errors: {
6092
+ 409: `Task cannot be resumed`
6093
+ }
6094
+ });
6095
+ }
6096
+ /**
6097
+ * List the latest 100 executions, newest first
6098
+ * @returns ScheduledTaskRun Executions; message acceptance does not imply agent completion
6099
+ * @throws ApiError
6100
+ */
6101
+ listScheduledTaskRuns({
6102
+ scheduledTaskId
6103
+ }) {
6104
+ return this.httpRequest.request({
6105
+ method: "GET",
6106
+ url: "/scheduled-tasks/{scheduledTaskId}/runs",
6107
+ path: {
6108
+ "scheduledTaskId": scheduledTaskId
6109
+ }
6110
+ });
6111
+ }
5546
6112
  /**
5547
6113
  * List organization service users
5548
6114
  * @returns ServiceUser Service users, which do not consume seats
@@ -5694,8 +6260,8 @@ var DefaultService = class {
5694
6260
  }
5695
6261
  /**
5696
6262
  * Delete snapshot
5697
- * Queue deletion of an unreferenced snapshot. Only its creator or the organization owner can delete it.
5698
- * @returns any Snapshot deletion queued
6263
+ * Remove a snapshot and its public publication. Imported copies and managed sandbox references remain usable. Enterprise members need the snapshot delete permission. Ordinary organizations allow its creator or owner to delete it.
6264
+ * @returns any Snapshot reference removed; provider cleanup is deferred
5699
6265
  * @throws ApiError
5700
6266
  */
5701
6267
  deleteSnapshot({
@@ -5733,6 +6299,147 @@ var DefaultService = class {
5733
6299
  }
5734
6300
  });
5735
6301
  }
6302
+ /**
6303
+ * Unpublish an organization snapshot
6304
+ * @returns void
6305
+ * @throws ApiError
6306
+ */
6307
+ unpublishSnapshot({
6308
+ snapshotUuid
6309
+ }) {
6310
+ return this.httpRequest.request({
6311
+ method: "DELETE",
6312
+ url: "/snapshots/{snapshotUUID}/publication",
6313
+ path: {
6314
+ "snapshotUUID": snapshotUuid
6315
+ },
6316
+ errors: {
6317
+ 403: `Forbidden`,
6318
+ 404: `Snapshot not found`
6319
+ }
6320
+ });
6321
+ }
6322
+ /**
6323
+ * Publish an organization snapshot
6324
+ * Publish a ready saved snapshot for other organizations to import. Enterprise members need the snapshot publish permission. Ordinary organizations allow its creator or owner to publish it.
6325
+ * @returns SnapshotPublication Publication ID (publishing again is idempotent)
6326
+ * @throws ApiError
6327
+ */
6328
+ publishSnapshot({
6329
+ snapshotUuid
6330
+ }) {
6331
+ return this.httpRequest.request({
6332
+ method: "PUT",
6333
+ url: "/snapshots/{snapshotUUID}/publication",
6334
+ path: {
6335
+ "snapshotUUID": snapshotUuid
6336
+ },
6337
+ errors: {
6338
+ 403: `Forbidden`,
6339
+ 404: `Snapshot not found`,
6340
+ 409: `Snapshot is not ready`
6341
+ }
6342
+ });
6343
+ }
6344
+ /**
6345
+ * Register additional exact SSO callback URLs
6346
+ * Requires active membership in the application's organization; enterprise permissions are enforced at the API layer. The application's https hostname with /auth/brazosd/callback is always registered. HTTPS is required except for loopback development callbacks.
6347
+ * @returns SSOAppConfiguration Configured callbacks
6348
+ * @throws ApiError
6349
+ */
6350
+ configureSsoApp({
6351
+ appId,
6352
+ requestBody
6353
+ }) {
6354
+ return this.httpRequest.request({
6355
+ method: "PUT",
6356
+ url: "/sso/apps/{appId}",
6357
+ path: {
6358
+ "appId": appId
6359
+ },
6360
+ body: requestBody,
6361
+ mediaType: "application/json"
6362
+ });
6363
+ }
6364
+ /**
6365
+ * Revoke a user grant using the application's service identity
6366
+ * @returns void
6367
+ * @throws ApiError
6368
+ */
6369
+ revokeSsoGrant({
6370
+ grantId
6371
+ }) {
6372
+ return this.httpRequest.request({
6373
+ method: "DELETE",
6374
+ url: "/sso/grants/{grantId}",
6375
+ path: {
6376
+ "grantId": grantId
6377
+ }
6378
+ });
6379
+ }
6380
+ /**
6381
+ * Rotate an application's organization-user credentials
6382
+ * Authenticates the application's service user as well as its SSO refresh credential. Previous token retries with the same requestId return the same result for two minutes. SSO refresh credentials cannot be used by ordinary refresh endpoints.
6383
+ * @returns SSOTokens Rotated credentials
6384
+ * @throws ApiError
6385
+ */
6386
+ refreshSsoTokens({
6387
+ requestBody
6388
+ }) {
6389
+ return this.httpRequest.request({
6390
+ method: "POST",
6391
+ url: "/sso/refresh",
6392
+ body: requestBody,
6393
+ mediaType: "application/json"
6394
+ });
6395
+ }
6396
+ /**
6397
+ * Begin an application login
6398
+ * Authenticate using the application's service user. The browser receives only a short-lived request ID; the service credential and PKCE verifier stay on the application server.
6399
+ * @returns SSORequest Login request
6400
+ * @throws ApiError
6401
+ */
6402
+ createSsoRequest({
6403
+ requestBody
6404
+ }) {
6405
+ return this.httpRequest.request({
6406
+ method: "POST",
6407
+ url: "/sso/requests",
6408
+ body: requestBody,
6409
+ mediaType: "application/json"
6410
+ });
6411
+ }
6412
+ /**
6413
+ * Preview a short-lived SSO request
6414
+ * @returns SSORequest Application and callback to display before authorization
6415
+ * @throws ApiError
6416
+ */
6417
+ getSsoRequest({
6418
+ requestId
6419
+ }) {
6420
+ return this.httpRequest.request({
6421
+ method: "GET",
6422
+ url: "/sso/requests/{requestId}",
6423
+ path: {
6424
+ "requestId": requestId
6425
+ }
6426
+ });
6427
+ }
6428
+ /**
6429
+ * Exchange a single-use authorization code
6430
+ * @returns SSOTokens Organization credentials or an application-specific identity JWT
6431
+ * @throws ApiError
6432
+ */
6433
+ exchangeSsoCode({
6434
+ requestBody
6435
+ }) {
6436
+ return this.httpRequest.request({
6437
+ method: "POST",
6438
+ url: "/sso/token",
6439
+ body: requestBody,
6440
+ mediaType: "application/json"
6441
+ });
6442
+ }
5736
6443
  /**
5737
6444
  * Get current org merchant profile
5738
6445
  * @returns TradeMerchant Merchant profile returned
@@ -6176,6 +6883,68 @@ var DefaultService3 = class {
6176
6883
  this.httpRequest = httpRequest;
6177
6884
  }
6178
6885
  httpRequest;
6886
+ /**
6887
+ * @returns CustomDomain Custom domains and DNS configuration
6888
+ * @throws ApiError
6889
+ */
6890
+ listAppDomains({
6891
+ id
6892
+ }) {
6893
+ return this.httpRequest.request({
6894
+ method: "GET",
6895
+ url: "/apps/{id}/domains",
6896
+ path: {
6897
+ "id": id
6898
+ },
6899
+ errors: {
6900
+ 404: `Function not found`
6901
+ }
6902
+ });
6903
+ }
6904
+ /**
6905
+ * @returns CustomDomain Domain reserved; configure both DNS records to begin verification
6906
+ * @throws ApiError
6907
+ */
6908
+ createAppDomain({
6909
+ id,
6910
+ requestBody
6911
+ }) {
6912
+ return this.httpRequest.request({
6913
+ method: "POST",
6914
+ url: "/apps/{id}/domains",
6915
+ path: {
6916
+ "id": id
6917
+ },
6918
+ body: requestBody,
6919
+ mediaType: "application/json",
6920
+ errors: {
6921
+ 400: `Invalid subdomain`,
6922
+ 404: `Function not found`,
6923
+ 409: `Domain already bound or function domain limit reached`,
6924
+ 503: `Custom domains unavailable`
6925
+ }
6926
+ });
6927
+ }
6928
+ /**
6929
+ * @returns void
6930
+ * @throws ApiError
6931
+ */
6932
+ deleteAppDomain({
6933
+ id,
6934
+ domainId
6935
+ }) {
6936
+ return this.httpRequest.request({
6937
+ method: "DELETE",
6938
+ url: "/apps/{id}/domains/{domainId}",
6939
+ path: {
6940
+ "id": id,
6941
+ "domainId": domainId
6942
+ },
6943
+ errors: {
6944
+ 404: `Domain not found`
6945
+ }
6946
+ });
6947
+ }
6179
6948
  /**
6180
6949
  * @returns string Serverless API contract; paths are relative to /api/v1/serverless.
6181
6950
  * @throws ApiError
@@ -6187,6 +6956,7 @@ var DefaultService3 = class {
6187
6956
  });
6188
6957
  }
6189
6958
  /**
6959
+ * Lists all undeleted functions in the caller's organization. Active organization members share management access; enterprise permissions belong to the API layer.
6190
6960
  * @returns AppSummary Success
6191
6961
  * @throws ApiError
6192
6962
  */
@@ -6283,18 +7053,100 @@ var DefaultService3 = class {
6283
7053
  id
6284
7054
  }) {
6285
7055
  return this.httpRequest.request({
6286
- method: "DELETE",
6287
- url: "/apps/{id}",
7056
+ method: "DELETE",
7057
+ url: "/apps/{id}",
7058
+ path: {
7059
+ "id": id
7060
+ },
7061
+ errors: {
7062
+ 400: `Invalid input`,
7063
+ 401: `Unauthorized`,
7064
+ 403: `Forbidden`,
7065
+ 404: `Not found`,
7066
+ 409: `Conflict`,
7067
+ 503: `Temporarily unavailable`
7068
+ }
7069
+ });
7070
+ }
7071
+ /**
7072
+ * Query cloud function stdout and stderr without waking the function
7073
+ * Queries retained container logs for current and stopped instances. Requires the same
7074
+ * active organization membership as getApp. Enterprise permissions belong to the API layer.
7075
+ * The interval is [from, to),
7076
+ * at most seven days, with to no later than the request time. Results are newest first.
7077
+ * Each response contains at most 100 entries and 1 MiB of JSON. Messages longer than
7078
+ * 32 KiB are previews with truncated=true and a short-lived downloadToken for the original.
7079
+ * Keep from, to and stream unchanged when following nextCursor. Cursors expire after
7080
+ * 15 minutes. An incomplete page contains no entries and a retry cursor at the same position.
7081
+ * Recent logs can arrive late: pagination is not a snapshot of SLS ingestion; refresh the
7082
+ * interval to include delayed logs. Retention is seven days, not archival storage.
7083
+ * Queries spanning more than 256 instances must use a narrower time range.
7084
+ *
7085
+ * @returns AppLogPage Bounded log page; inspect status before treating it as complete.
7086
+ * @throws ApiError
7087
+ */
7088
+ listAppLogs({
7089
+ id,
7090
+ from,
7091
+ to,
7092
+ limit = 100,
7093
+ stream,
7094
+ cursor
7095
+ }) {
7096
+ return this.httpRequest.request({
7097
+ method: "GET",
7098
+ url: "/apps/{id}/logs",
7099
+ path: {
7100
+ "id": id
7101
+ },
7102
+ query: {
7103
+ "from": from,
7104
+ "to": to,
7105
+ "limit": limit,
7106
+ "stream": stream,
7107
+ "cursor": cursor
7108
+ },
7109
+ errors: {
7110
+ 400: `Invalid time range, limit or cursor`,
7111
+ 401: `Unauthorized`,
7112
+ 403: `Forbidden`,
7113
+ 404: `Function not found`,
7114
+ 409: `Instance mapping changed; restart the query`,
7115
+ 410: `Cursor expired; restart the query`,
7116
+ 422: `Too many instances; narrow the time range`,
7117
+ 502: `Log provider failed; this is not an empty result`,
7118
+ 503: `Log collection query is not configured`
7119
+ }
7120
+ });
7121
+ }
7122
+ /**
7123
+ * Download one original log message referenced by a truncated preview
7124
+ * @returns binary Original UTF-8 log message, served as an attachment.
7125
+ * @throws ApiError
7126
+ */
7127
+ downloadAppLogContent({
7128
+ id,
7129
+ token
7130
+ }) {
7131
+ return this.httpRequest.request({
7132
+ method: "GET",
7133
+ url: "/apps/{id}/logs/content",
6288
7134
  path: {
6289
7135
  "id": id
6290
7136
  },
7137
+ query: {
7138
+ "token": token
7139
+ },
6291
7140
  errors: {
6292
- 400: `Invalid input`,
7141
+ 400: `Invalid token`,
6293
7142
  401: `Unauthorized`,
6294
7143
  403: `Forbidden`,
6295
- 404: `Not found`,
6296
- 409: `Conflict`,
6297
- 503: `Temporarily unavailable`
7144
+ 404: `Function or retained log no longer exists`,
7145
+ 409: `Log position changed; restart the query`,
7146
+ 410: `Token expired; restart the query`,
7147
+ 422: `Too many instances; narrow the time range and query again`,
7148
+ 502: `Log provider failed`,
7149
+ 503: `Logs unavailable or provider query incomplete; retry later`
6298
7150
  }
6299
7151
  });
6300
7152
  }
@@ -6655,33 +7507,6 @@ var ServerlessClient = class {
6655
7507
  }
6656
7508
  };
6657
7509
 
6658
- // src/credentials.ts
6659
- import { readFile } from "node:fs/promises";
6660
- var DEFAULT_CREDENTIALS_FILE = "/run/brazosd/identity/credentials.json";
6661
- function fileCredentials(path = DEFAULT_CREDENTIALS_FILE) {
6662
- let cached;
6663
- let cacheUntil = 0;
6664
- let pending;
6665
- return () => {
6666
- if (cached && Date.now() < cacheUntil) return Promise.resolve(cached);
6667
- if (!pending) {
6668
- pending = readFile(path, "utf8").then((raw) => {
6669
- const value = JSON.parse(raw);
6670
- const expiresAt = Date.parse(value.expiresAt);
6671
- if (typeof value.accessToken !== "string" || !value.accessToken || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
6672
- throw new Error("Brazosd instance credentials are missing or expired");
6673
- }
6674
- cached = { accessToken: value.accessToken, apiUrl: value.apiUrl, expiresAt: value.expiresAt };
6675
- cacheUntil = Math.min(Date.now() + 1e3, expiresAt);
6676
- return cached;
6677
- }).finally(() => {
6678
- pending = void 0;
6679
- });
6680
- }
6681
- return pending;
6682
- };
6683
- }
6684
-
6685
7510
  // src/generated/operations.ts
6686
7511
  var operations = {
6687
7512
  "api": {
@@ -6881,6 +7706,27 @@ var operations = {
6881
7706
  "401": "void"
6882
7707
  }
6883
7708
  },
7709
+ "GET /account/sso/grants": {
7710
+ "authenticated": true,
7711
+ "redirect": false,
7712
+ "responses": {
7713
+ "200": "json"
7714
+ }
7715
+ },
7716
+ "DELETE /account/sso/grants/{grantId}": {
7717
+ "authenticated": true,
7718
+ "redirect": false,
7719
+ "responses": {
7720
+ "204": "void"
7721
+ }
7722
+ },
7723
+ "POST /account/sso/requests/{requestId}/authorize": {
7724
+ "authenticated": true,
7725
+ "redirect": false,
7726
+ "responses": {
7727
+ "200": "json"
7728
+ }
7729
+ },
6884
7730
  "DELETE /agent-contact-list/{agentId}": {
6885
7731
  "authenticated": true,
6886
7732
  "redirect": false,
@@ -7047,6 +7893,50 @@ var operations = {
7047
7893
  "404": "void"
7048
7894
  }
7049
7895
  },
7896
+ "POST /agent-sessions/{sessionId}/client-mcp-results/{runId}/{toolCallId}": {
7897
+ "authenticated": true,
7898
+ "redirect": false,
7899
+ "responses": {
7900
+ "204": "void",
7901
+ "400": "void",
7902
+ "403": "void",
7903
+ "404": "void",
7904
+ "409": "void"
7905
+ }
7906
+ },
7907
+ "GET /agent-sessions/{sessionId}/client-mcps": {
7908
+ "authenticated": true,
7909
+ "redirect": false,
7910
+ "responses": {
7911
+ "200": "json",
7912
+ "400": "void",
7913
+ "403": "void",
7914
+ "404": "void",
7915
+ "409": "void"
7916
+ }
7917
+ },
7918
+ "DELETE /agent-sessions/{sessionId}/client-mcps/{namespace}": {
7919
+ "authenticated": true,
7920
+ "redirect": false,
7921
+ "responses": {
7922
+ "204": "void",
7923
+ "400": "void",
7924
+ "403": "void",
7925
+ "404": "void",
7926
+ "409": "void"
7927
+ }
7928
+ },
7929
+ "PUT /agent-sessions/{sessionId}/client-mcps/{namespace}": {
7930
+ "authenticated": true,
7931
+ "redirect": false,
7932
+ "responses": {
7933
+ "200": "json",
7934
+ "400": "void",
7935
+ "403": "void",
7936
+ "404": "void",
7937
+ "409": "void"
7938
+ }
7939
+ },
7050
7940
  "POST /agent-sessions/{sessionId}/compact": {
7051
7941
  "authenticated": true,
7052
7942
  "redirect": false,
@@ -7100,6 +7990,16 @@ var operations = {
7100
7990
  "409": "void"
7101
7991
  }
7102
7992
  },
7993
+ "POST /agent-sessions/{sessionId}/interrupt-tree": {
7994
+ "authenticated": true,
7995
+ "redirect": false,
7996
+ "responses": {
7997
+ "200": "json",
7998
+ "403": "void",
7999
+ "404": "void",
8000
+ "409": "json"
8001
+ }
8002
+ },
7103
8003
  "PUT /agent-sessions/{sessionId}/llm-model": {
7104
8004
  "authenticated": true,
7105
8005
  "redirect": false,
@@ -7110,6 +8010,28 @@ var operations = {
7110
8010
  "404": "void"
7111
8011
  }
7112
8012
  },
8013
+ "POST /agent-sessions/{sessionId}/resume": {
8014
+ "authenticated": true,
8015
+ "redirect": false,
8016
+ "responses": {
8017
+ "202": "json",
8018
+ "402": "void",
8019
+ "403": "void",
8020
+ "404": "void",
8021
+ "409": "json"
8022
+ }
8023
+ },
8024
+ "POST /agent-sessions/{sessionId}/resume-tree": {
8025
+ "authenticated": true,
8026
+ "redirect": false,
8027
+ "responses": {
8028
+ "202": "json",
8029
+ "402": "void",
8030
+ "403": "void",
8031
+ "404": "void",
8032
+ "409": "json"
8033
+ }
8034
+ },
7113
8035
  "DELETE /agent-sessions/{sessionId}/share": {
7114
8036
  "authenticated": true,
7115
8037
  "redirect": false,
@@ -7148,6 +8070,16 @@ var operations = {
7148
8070
  "409": "void"
7149
8071
  }
7150
8072
  },
8073
+ "PUT /agent-sessions/{sessionId}/title": {
8074
+ "authenticated": true,
8075
+ "redirect": false,
8076
+ "responses": {
8077
+ "200": "json",
8078
+ "400": "void",
8079
+ "403": "void",
8080
+ "404": "void"
8081
+ }
8082
+ },
7151
8083
  "GET /agent-sessions/{sessionId}/todo-list": {
7152
8084
  "authenticated": true,
7153
8085
  "redirect": false,
@@ -7376,6 +8308,26 @@ var operations = {
7376
8308
  "404": "void"
7377
8309
  }
7378
8310
  },
8311
+ "GET /agents/{agentId}/tool-settings": {
8312
+ "authenticated": true,
8313
+ "redirect": false,
8314
+ "responses": {
8315
+ "200": "json",
8316
+ "400": "void",
8317
+ "403": "void",
8318
+ "404": "void"
8319
+ }
8320
+ },
8321
+ "PUT /agents/{agentId}/tool-settings": {
8322
+ "authenticated": true,
8323
+ "redirect": false,
8324
+ "responses": {
8325
+ "200": "json",
8326
+ "400": "void",
8327
+ "403": "void",
8328
+ "404": "void"
8329
+ }
8330
+ },
7379
8331
  "GET /agents/{agentId}/trdp-markup": {
7380
8332
  "authenticated": true,
7381
8333
  "redirect": false,
@@ -7905,6 +8857,7 @@ var operations = {
7905
8857
  "404": "void",
7906
8858
  "409": "void",
7907
8859
  "412": "void",
8860
+ "413": "void",
7908
8861
  "429": "void",
7909
8862
  "503": "void"
7910
8863
  }
@@ -8176,6 +9129,18 @@ var operations = {
8176
9129
  "501": "void"
8177
9130
  }
8178
9131
  },
9132
+ "PUT /devices/{deviceId}/scope": {
9133
+ "authenticated": true,
9134
+ "redirect": false,
9135
+ "responses": {
9136
+ "200": "json",
9137
+ "400": "void",
9138
+ "401": "void",
9139
+ "403": "void",
9140
+ "404": "void",
9141
+ "503": "void"
9142
+ }
9143
+ },
8179
9144
  "POST /devices/{deviceId}/token": {
8180
9145
  "authenticated": true,
8181
9146
  "redirect": false,
@@ -8753,6 +9718,14 @@ var operations = {
8753
9718
  "404": "void"
8754
9719
  }
8755
9720
  },
9721
+ "GET /org/permissions": {
9722
+ "authenticated": true,
9723
+ "redirect": false,
9724
+ "responses": {
9725
+ "200": "json",
9726
+ "401": "void"
9727
+ }
9728
+ },
8756
9729
  "GET /org/quotas": {
8757
9730
  "authenticated": true,
8758
9731
  "redirect": false,
@@ -8761,6 +9734,25 @@ var operations = {
8761
9734
  "401": "void"
8762
9735
  }
8763
9736
  },
9737
+ "GET /org/users/{userId}/daily-budget": {
9738
+ "authenticated": true,
9739
+ "redirect": false,
9740
+ "responses": {
9741
+ "200": "json",
9742
+ "403": "void",
9743
+ "404": "void"
9744
+ }
9745
+ },
9746
+ "PUT /org/users/{userId}/daily-budget": {
9747
+ "authenticated": true,
9748
+ "redirect": false,
9749
+ "responses": {
9750
+ "200": "json",
9751
+ "400": "void",
9752
+ "403": "void",
9753
+ "404": "void"
9754
+ }
9755
+ },
8764
9756
  "GET /org/users/{userId}/enterprise-permission-policies": {
8765
9757
  "authenticated": true,
8766
9758
  "redirect": false,
@@ -8844,6 +9836,22 @@ var operations = {
8844
9836
  "404": "void"
8845
9837
  }
8846
9838
  },
9839
+ "GET /public-snapshots": {
9840
+ "authenticated": true,
9841
+ "redirect": false,
9842
+ "responses": {
9843
+ "200": "json"
9844
+ }
9845
+ },
9846
+ "POST /public-snapshots/{publicationID}/copies": {
9847
+ "authenticated": true,
9848
+ "redirect": false,
9849
+ "responses": {
9850
+ "201": "json",
9851
+ "402": "void",
9852
+ "404": "void"
9853
+ }
9854
+ },
8847
9855
  "GET /public/agents/{agentRepoId}": {
8848
9856
  "authenticated": false,
8849
9857
  "redirect": false,
@@ -8937,6 +9945,70 @@ var operations = {
8937
9945
  "404": "void"
8938
9946
  }
8939
9947
  },
9948
+ "GET /scheduled-tasks": {
9949
+ "authenticated": true,
9950
+ "redirect": false,
9951
+ "responses": {
9952
+ "200": "json"
9953
+ }
9954
+ },
9955
+ "POST /scheduled-tasks": {
9956
+ "authenticated": true,
9957
+ "redirect": false,
9958
+ "responses": {
9959
+ "201": "json",
9960
+ "400": "void",
9961
+ "403": "void",
9962
+ "409": "void"
9963
+ }
9964
+ },
9965
+ "DELETE /scheduled-tasks/{scheduledTaskId}": {
9966
+ "authenticated": true,
9967
+ "redirect": false,
9968
+ "responses": {
9969
+ "204": "void"
9970
+ }
9971
+ },
9972
+ "GET /scheduled-tasks/{scheduledTaskId}": {
9973
+ "authenticated": true,
9974
+ "redirect": false,
9975
+ "responses": {
9976
+ "200": "json",
9977
+ "404": "void"
9978
+ }
9979
+ },
9980
+ "PUT /scheduled-tasks/{scheduledTaskId}": {
9981
+ "authenticated": true,
9982
+ "redirect": false,
9983
+ "responses": {
9984
+ "200": "json",
9985
+ "400": "void",
9986
+ "409": "void"
9987
+ }
9988
+ },
9989
+ "POST /scheduled-tasks/{scheduledTaskId}/pause": {
9990
+ "authenticated": true,
9991
+ "redirect": false,
9992
+ "responses": {
9993
+ "200": "json",
9994
+ "409": "void"
9995
+ }
9996
+ },
9997
+ "POST /scheduled-tasks/{scheduledTaskId}/resume": {
9998
+ "authenticated": true,
9999
+ "redirect": false,
10000
+ "responses": {
10001
+ "200": "json",
10002
+ "409": "void"
10003
+ }
10004
+ },
10005
+ "GET /scheduled-tasks/{scheduledTaskId}/runs": {
10006
+ "authenticated": true,
10007
+ "redirect": false,
10008
+ "responses": {
10009
+ "200": "json"
10010
+ }
10011
+ },
8940
10012
  "GET /service-users": {
8941
10013
  "authenticated": true,
8942
10014
  "redirect": false,
@@ -9016,6 +10088,67 @@ var operations = {
9016
10088
  "404": "void"
9017
10089
  }
9018
10090
  },
10091
+ "DELETE /snapshots/{snapshotUUID}/publication": {
10092
+ "authenticated": true,
10093
+ "redirect": false,
10094
+ "responses": {
10095
+ "204": "void",
10096
+ "403": "void",
10097
+ "404": "void"
10098
+ }
10099
+ },
10100
+ "PUT /snapshots/{snapshotUUID}/publication": {
10101
+ "authenticated": true,
10102
+ "redirect": false,
10103
+ "responses": {
10104
+ "200": "json",
10105
+ "403": "void",
10106
+ "404": "void",
10107
+ "409": "void"
10108
+ }
10109
+ },
10110
+ "PUT /sso/apps/{appId}": {
10111
+ "authenticated": true,
10112
+ "redirect": false,
10113
+ "responses": {
10114
+ "200": "json"
10115
+ }
10116
+ },
10117
+ "DELETE /sso/grants/{grantId}": {
10118
+ "authenticated": true,
10119
+ "redirect": false,
10120
+ "responses": {
10121
+ "204": "void"
10122
+ }
10123
+ },
10124
+ "POST /sso/refresh": {
10125
+ "authenticated": true,
10126
+ "redirect": false,
10127
+ "responses": {
10128
+ "200": "json"
10129
+ }
10130
+ },
10131
+ "POST /sso/requests": {
10132
+ "authenticated": true,
10133
+ "redirect": false,
10134
+ "responses": {
10135
+ "201": "json"
10136
+ }
10137
+ },
10138
+ "GET /sso/requests/{requestId}": {
10139
+ "authenticated": false,
10140
+ "redirect": false,
10141
+ "responses": {
10142
+ "200": "json"
10143
+ }
10144
+ },
10145
+ "POST /sso/token": {
10146
+ "authenticated": true,
10147
+ "redirect": false,
10148
+ "responses": {
10149
+ "200": "json"
10150
+ }
10151
+ },
9019
10152
  "GET /trade/merchant": {
9020
10153
  "authenticated": true,
9021
10154
  "redirect": false,
@@ -9206,6 +10339,33 @@ var operations = {
9206
10339
  }
9207
10340
  },
9208
10341
  "serverless": {
10342
+ "GET /apps/{id}/domains": {
10343
+ "authenticated": true,
10344
+ "redirect": false,
10345
+ "responses": {
10346
+ "200": "json",
10347
+ "404": "void"
10348
+ }
10349
+ },
10350
+ "POST /apps/{id}/domains": {
10351
+ "authenticated": true,
10352
+ "redirect": false,
10353
+ "responses": {
10354
+ "201": "json",
10355
+ "400": "void",
10356
+ "404": "void",
10357
+ "409": "void",
10358
+ "503": "void"
10359
+ }
10360
+ },
10361
+ "DELETE /apps/{id}/domains/{domainId}": {
10362
+ "authenticated": true,
10363
+ "redirect": false,
10364
+ "responses": {
10365
+ "204": "void",
10366
+ "404": "void"
10367
+ }
10368
+ },
9209
10369
  "GET /openapi.yaml": {
9210
10370
  "authenticated": false,
9211
10371
  "redirect": false,
@@ -9278,6 +10438,38 @@ var operations = {
9278
10438
  "503": "void"
9279
10439
  }
9280
10440
  },
10441
+ "GET /apps/{id}/logs": {
10442
+ "authenticated": true,
10443
+ "redirect": false,
10444
+ "responses": {
10445
+ "200": "json",
10446
+ "400": "void",
10447
+ "401": "void",
10448
+ "403": "void",
10449
+ "404": "void",
10450
+ "409": "void",
10451
+ "410": "void",
10452
+ "422": "void",
10453
+ "502": "void",
10454
+ "503": "void"
10455
+ }
10456
+ },
10457
+ "GET /apps/{id}/logs/content": {
10458
+ "authenticated": true,
10459
+ "redirect": false,
10460
+ "responses": {
10461
+ "200": "stream",
10462
+ "400": "void",
10463
+ "401": "void",
10464
+ "403": "void",
10465
+ "404": "void",
10466
+ "409": "void",
10467
+ "410": "void",
10468
+ "422": "void",
10469
+ "502": "void",
10470
+ "503": "void"
10471
+ }
10472
+ },
9281
10473
  "PUT /apps/{id}/databases/{databaseId}": {
9282
10474
  "authenticated": true,
9283
10475
  "redirect": false,
@@ -9501,6 +10693,20 @@ async function rejectResponse(response) {
9501
10693
  }
9502
10694
  throw new BrazosdError(response.status, `Brazosd API returned HTTP ${response.status}`, body);
9503
10695
  }
10696
+ async function realtimeURL(context) {
10697
+ const authorization = new Headers(context.headers).get("Authorization");
10698
+ const credential = !authorization || !context.apiUrl ? await context.credentials() : void 0;
10699
+ const token = authorization?.replace(/^Bearer\s+/i, "") ?? credential?.accessToken;
10700
+ if (!token || credential?.expiresAt && !(Date.parse(credential.expiresAt) > Date.now())) {
10701
+ throw new Error("Brazosd credentials are missing or expired");
10702
+ }
10703
+ const url = new URL(context.apiUrl ?? apiURL(credential.apiUrl));
10704
+ const path = url.pathname.replace(/\/+$/, "");
10705
+ url.pathname = path.endsWith("/api/v1") ? path.slice(0, -7) + "/ws" : "/ws";
10706
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
10707
+ url.searchParams.set("access_token", token);
10708
+ return url.toString();
10709
+ }
9504
10710
  function createRequest(context, kind) {
9505
10711
  return class AuthenticatedRequest extends BaseHttpRequest {
9506
10712
  request(options) {
@@ -9573,31 +10779,780 @@ async function execute(context, kind, options, signal) {
9573
10779
  return response.text();
9574
10780
  }
9575
10781
 
9576
- // src/index.ts
10782
+ // src/client-mcp.ts
10783
+ var pageSize = 100;
10784
+ var receiptLimit = 1024;
10785
+ var errorResult = (message) => ({ isError: true, content: [{ type: "text", text: message }] });
10786
+ var asError = (value) => value instanceof Error ? value : new Error(String(value));
10787
+ function webMCPResult(value) {
10788
+ const encoded = JSON.stringify(value);
10789
+ if (encoded === void 0) throw new Error("WebMCP callbacks must return a JSON-serializable value");
10790
+ const result = JSON.parse(encoded);
10791
+ if (result && Array.isArray(result.content)) return result;
10792
+ return {
10793
+ content: [{ type: "text", text: typeof result === "string" ? result : encoded }],
10794
+ ...result !== null && typeof result === "object" && !Array.isArray(result) ? { structuredContent: result } : {}
10795
+ };
10796
+ }
10797
+ function delay(ms, signal) {
10798
+ return new Promise((resolve2, reject) => {
10799
+ if (signal.aborted) {
10800
+ reject(signal.reason);
10801
+ return;
10802
+ }
10803
+ const abort = () => {
10804
+ clearTimeout(timer);
10805
+ reject(signal.reason);
10806
+ };
10807
+ const timer = setTimeout(() => {
10808
+ signal.removeEventListener("abort", abort);
10809
+ resolve2();
10810
+ }, ms);
10811
+ signal.addEventListener("abort", abort, { once: true });
10812
+ });
10813
+ }
10814
+ async function request2(pending, signal) {
10815
+ const abort = () => pending.cancel();
10816
+ if (signal.aborted) abort();
10817
+ else signal.addEventListener("abort", abort, { once: true });
10818
+ try {
10819
+ return await pending;
10820
+ } finally {
10821
+ signal.removeEventListener("abort", abort);
10822
+ }
10823
+ }
10824
+ var ClientMCPBridge = class {
10825
+ constructor(api, sessionId, socketURL, options = {}) {
10826
+ this.api = api;
10827
+ this.sessionId = sessionId;
10828
+ this.socketURL = socketURL;
10829
+ this.options = options;
10830
+ this.signal = options.signal ? AbortSignal.any([options.signal, this.controller.signal]) : this.controller.signal;
10831
+ this.storageKey = `brazosd:client-mcp:v1:${sessionId}`;
10832
+ if (options.storage) {
10833
+ try {
10834
+ const cached = JSON.parse(options.storage.getItem(this.storageKey) ?? "[]");
10835
+ if (!Array.isArray(cached) || cached.some((value) => typeof value !== "string")) throw new Error("Invalid client MCP receipt cache");
10836
+ for (const key of cached.slice(-receiptLimit)) this.receipts.add(key);
10837
+ } catch (error) {
10838
+ this.report(error);
10839
+ }
10840
+ }
10841
+ }
10842
+ api;
10843
+ sessionId;
10844
+ socketURL;
10845
+ options;
10846
+ controller = new AbortController();
10847
+ signal;
10848
+ callbacks = /* @__PURE__ */ new Map();
10849
+ installations = /* @__PURE__ */ new Map();
10850
+ definitions = /* @__PURE__ */ new Map();
10851
+ registrationCleanups = /* @__PURE__ */ new Map();
10852
+ mutation = Promise.resolve();
10853
+ pending = /* @__PURE__ */ new Map();
10854
+ receipts = /* @__PURE__ */ new Set();
10855
+ storageKey;
10856
+ socket;
10857
+ connection;
10858
+ online = false;
10859
+ cursor = 0;
10860
+ buffer = [];
10861
+ syncing;
10862
+ catchUp = false;
10863
+ /** Registers one named tool in this bridge's namespace, following WebMCP's declaration shape. */
10864
+ registerTool(tool, options = {}) {
10865
+ return this.mutate(async () => {
10866
+ this.signal.throwIfAborted();
10867
+ options.signal?.throwIfAborted();
10868
+ const namespace = this.options.namespace ?? "browser";
10869
+ const current = this.definitions.get(namespace) ?? {};
10870
+ if (Object.hasOwn(current, tool.name)) throw new Error(`Client MCP tool already registered: ${tool.name}`);
10871
+ const callback = {
10872
+ description: tool.description,
10873
+ inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
10874
+ execute: async (args, context) => {
10875
+ const signal = options.signal ? AbortSignal.any([context.signal, options.signal]) : context.signal;
10876
+ signal.throwIfAborted();
10877
+ return webMCPResult(await tool.execute(args, { ...context, signal }));
10878
+ }
10879
+ };
10880
+ await this.installTools(namespace, { ...current, [tool.name]: callback });
10881
+ if (options.signal) {
10882
+ const abort = () => {
10883
+ void this.mutate(async () => {
10884
+ const installed = this.definitions.get(namespace);
10885
+ if (installed?.[tool.name] !== callback) return;
10886
+ const remaining = { ...installed };
10887
+ delete remaining[tool.name];
10888
+ if (Object.keys(remaining).length) await this.installTools(namespace, remaining);
10889
+ else await this.uninstallTools(namespace);
10890
+ }).catch((error) => {
10891
+ if (!this.signal.aborted) this.report(error);
10892
+ });
10893
+ };
10894
+ this.registrationCleanups.set(callback, () => {
10895
+ options.signal.removeEventListener("abort", abort);
10896
+ this.registrationCleanups.delete(callback);
10897
+ });
10898
+ options.signal.addEventListener("abort", abort, { once: true });
10899
+ if (options.signal.aborted) abort();
10900
+ }
10901
+ });
10902
+ }
10903
+ install(namespace, tools) {
10904
+ return this.mutate(() => this.installTools(namespace, tools));
10905
+ }
10906
+ async installTools(namespace, tools) {
10907
+ const prefix = `clientmcp_${namespace}_`;
10908
+ const registrations = Object.entries(tools).map(([name, tool]) => [prefix + name.replaceAll(".", "_"), tool]);
10909
+ const names = new Set(registrations.map(([name]) => name));
10910
+ if (names.size !== registrations.length) throw new Error("Duplicate client MCP tool names after normalization");
10911
+ for (const [installed, registered] of this.installations) {
10912
+ if (installed !== namespace && [...names].some((name) => registered.has(name))) throw new Error("Client MCP tool name already registered");
10913
+ }
10914
+ const previous = new Map(registrations.map(([name]) => [name, this.callbacks.get(name)]));
10915
+ for (const [name, tool] of registrations) this.callbacks.set(name, tool);
10916
+ try {
10917
+ const installation = await request2(this.api.installAgentSessionClientMcp({ sessionId: this.sessionId, namespace, requestBody: {
10918
+ tools: Object.entries(tools).map(([name, tool]) => ({ name, description: tool.description, inputSchema: tool.inputSchema }))
10919
+ } }), this.signal);
10920
+ for (const name of this.installations.get(namespace) ?? []) if (!names.has(name)) this.callbacks.delete(name);
10921
+ for (const [name, old] of Object.entries(this.definitions.get(namespace) ?? {})) {
10922
+ if (tools[name] !== old) this.registrationCleanups.get(old)?.();
10923
+ }
10924
+ this.installations.set(namespace, names);
10925
+ this.definitions.set(namespace, { ...tools });
10926
+ return installation;
10927
+ } catch (error) {
10928
+ for (const [name, callback] of previous) {
10929
+ if (callback) this.callbacks.set(name, callback);
10930
+ else this.callbacks.delete(name);
10931
+ }
10932
+ throw error;
10933
+ }
10934
+ }
10935
+ uninstall(namespace) {
10936
+ return this.mutate(() => this.uninstallTools(namespace));
10937
+ }
10938
+ async uninstallTools(namespace) {
10939
+ await request2(this.api.uninstallAgentSessionClientMcp({ sessionId: this.sessionId, namespace }), this.signal);
10940
+ for (const name of this.installations.get(namespace) ?? []) this.callbacks.delete(name);
10941
+ for (const callback of Object.values(this.definitions.get(namespace) ?? {})) this.registrationCleanups.get(callback)?.();
10942
+ this.installations.delete(namespace);
10943
+ this.definitions.delete(namespace);
10944
+ }
10945
+ mutate(operation) {
10946
+ const result = this.mutation.then(operation);
10947
+ this.mutation = result.catch(() => void 0);
10948
+ return result;
10949
+ }
10950
+ /** Resolves after subscription ACK and canonical history catch-up. Reconnects automatically thereafter. */
10951
+ connect() {
10952
+ if (!this.connection) {
10953
+ this.connection = new Promise((resolve2, reject) => {
10954
+ void this.run(resolve2).then(() => reject(this.signal.reason ?? new Error("Client MCP bridge closed")), reject);
10955
+ });
10956
+ }
10957
+ return this.connection;
10958
+ }
10959
+ /** Stops communication and aborts callback signals. Installations remain for refresh/reconnect. */
10960
+ close() {
10961
+ this.controller.abort(new Error("Client MCP bridge closed"));
10962
+ this.socket?.close();
10963
+ for (const cleanup of this.registrationCleanups.values()) cleanup();
10964
+ }
10965
+ report(error) {
10966
+ if (this.options.onError) this.options.onError(asError(error));
10967
+ else console.error("Brazosd client MCP:", asError(error));
10968
+ }
10969
+ async run(ready) {
10970
+ let failures = 0;
10971
+ while (!this.signal.aborted) {
10972
+ try {
10973
+ await this.openSocket(() => {
10974
+ failures = 0;
10975
+ ready();
10976
+ });
10977
+ } catch (error) {
10978
+ if (this.signal.aborted) break;
10979
+ this.report(error);
10980
+ if (error instanceof SubscriptionRejected) throw error;
10981
+ await delay(Math.min(1e3 * 2 ** Math.min(failures++, 5), 3e4), this.signal);
10982
+ }
10983
+ }
10984
+ }
10985
+ async openSocket(ready) {
10986
+ const url = await this.socketURL();
10987
+ this.signal.throwIfAborted();
10988
+ const socket = this.options.webSocketFactory?.(url) ?? new WebSocket(url);
10989
+ this.socket = socket;
10990
+ const connection = new AbortController();
10991
+ const signal = AbortSignal.any([this.signal, connection.signal]);
10992
+ const topic = `agent_session_events:${this.sessionId}`;
10993
+ this.buffer = [];
10994
+ return new Promise((resolve2, reject) => {
10995
+ let ended = false;
10996
+ let pingPending = false;
10997
+ let heartbeat;
10998
+ const timeout = setTimeout(() => finish(new Error("Client MCP subscription timed out")), 15e3);
10999
+ const finish = (error) => {
11000
+ if (ended) return;
11001
+ ended = true;
11002
+ this.online = false;
11003
+ clearTimeout(timeout);
11004
+ clearInterval(heartbeat);
11005
+ this.signal.removeEventListener("abort", abort);
11006
+ connection.abort();
11007
+ socket.close();
11008
+ if (error) reject(error);
11009
+ else resolve2();
11010
+ };
11011
+ const abort = () => finish();
11012
+ this.signal.addEventListener("abort", abort, { once: true });
11013
+ socket.onopen = () => socket.send(JSON.stringify({ id: "client-mcp", type: "subscribe", payload: { subscribe: { topic } } }));
11014
+ socket.onclose = () => finish(new Error("Client MCP websocket disconnected"));
11015
+ socket.onerror = () => finish(new Error("Client MCP websocket error"));
11016
+ socket.onmessage = (event) => {
11017
+ if (ended) return;
11018
+ try {
11019
+ const frame = JSON.parse(String(event.data));
11020
+ if (frame.type === "ping") {
11021
+ pingPending = false;
11022
+ return;
11023
+ }
11024
+ if (frame.type === "error") {
11025
+ const message = frame.payload?.error?.msg ?? "Client MCP subscription failed";
11026
+ finish(frame.payload?.error?.retryable === false ? new SubscriptionRejected(message) : new Error(message));
11027
+ } else if (frame.type === "success" && frame.id === "client-mcp") {
11028
+ clearTimeout(timeout);
11029
+ heartbeat = setInterval(() => {
11030
+ if (pingPending) {
11031
+ finish(new Error("Client MCP heartbeat timed out"));
11032
+ return;
11033
+ }
11034
+ pingPending = true;
11035
+ socket.send(JSON.stringify({ id: "heartbeat", type: "ping" }));
11036
+ }, 15e3);
11037
+ void this.synchronize(signal, true).then(() => {
11038
+ if (ended) return;
11039
+ this.online = true;
11040
+ this.dispatch();
11041
+ ready();
11042
+ }, (error) => finish(asError(error)));
11043
+ } else if (frame.type === "event") {
11044
+ const event2 = frame.payload?.event;
11045
+ if (event2?.topic === "agent_session_events" && event2.data?.sessionId === this.sessionId) {
11046
+ this.buffer.push(event2.data);
11047
+ if (this.buffer.length > 4096) {
11048
+ this.buffer = [];
11049
+ this.catchUp = true;
11050
+ }
11051
+ if (this.online) void this.synchronize(signal).catch((error) => finish(asError(error)));
11052
+ } else if (event2?.topic === "realtime_resync") {
11053
+ if (event2.data?.resubscribe && event2.data?.topics?.includes(topic)) {
11054
+ finish(new Error("Client MCP event reader requires resubscription"));
11055
+ } else {
11056
+ void this.synchronize(signal, true).catch((error) => finish(asError(error)));
11057
+ }
11058
+ }
11059
+ }
11060
+ } catch (error) {
11061
+ finish(asError(error));
11062
+ }
11063
+ };
11064
+ if (this.signal.aborted) finish();
11065
+ });
11066
+ }
11067
+ synchronize(signal, catchUp = false) {
11068
+ this.catchUp ||= catchUp;
11069
+ if (this.syncing) return this.syncing;
11070
+ this.syncing = (async () => {
11071
+ do {
11072
+ if (this.catchUp) {
11073
+ this.catchUp = false;
11074
+ await this.loadHistory(signal);
11075
+ }
11076
+ const events = this.buffer.splice(0).sort((a, b) => (a.serialNumber ?? 0) - (b.serialNumber ?? 0));
11077
+ for (const event of events) {
11078
+ if (event.sessionId !== this.sessionId || !event.serialNumber) continue;
11079
+ if (event.serialNumber > this.cursor + 1) await this.loadHistory(signal);
11080
+ if (event.serialNumber > this.cursor + 1) throw new Error("Gap in client MCP session history");
11081
+ this.consume(event);
11082
+ }
11083
+ } while (this.buffer.length || this.catchUp);
11084
+ })().finally(() => {
11085
+ this.syncing = void 0;
11086
+ });
11087
+ return this.syncing.then(() => {
11088
+ if (this.buffer.length || this.catchUp) return this.synchronize(signal);
11089
+ this.dispatch();
11090
+ });
11091
+ }
11092
+ async loadHistory(signal) {
11093
+ for (; ; ) {
11094
+ const events = await request2(this.api.getAgentSessionEvents({ sessionId: this.sessionId, from: this.cursor + 1, limit: pageSize }), signal);
11095
+ signal.throwIfAborted();
11096
+ const before = this.cursor;
11097
+ for (const event of events) this.consume(event);
11098
+ if (events.length < pageSize) return;
11099
+ if (this.cursor <= before) throw new Error("Session history did not advance");
11100
+ }
11101
+ }
11102
+ consume(event) {
11103
+ if (event.sessionId !== this.sessionId || !event.serialNumber || event.serialNumber <= this.cursor) return;
11104
+ this.cursor = event.serialNumber;
11105
+ if (event.eventType === "session_archived" || event.eventType === "session_forked" && event.event.forkedSessionId === this.sessionId) {
11106
+ for (const key2 of this.pending.keys()) this.complete(key2);
11107
+ return;
11108
+ }
11109
+ if (!event.runId) return;
11110
+ if (["agent_end", "interrupt", "run_stopped"].includes(event.eventType)) {
11111
+ for (const [key2, call] of this.pending) if (call.context.runId === event.runId) this.complete(key2);
11112
+ return;
11113
+ }
11114
+ const data = event.event;
11115
+ if (typeof data.toolCallId !== "string") return;
11116
+ const key = `${this.sessionId}:${event.runId}:${data.toolCallId}`;
11117
+ if (["tool_result", "tool_execution_end"].includes(event.eventType)) {
11118
+ if (this.pending.has(key) || String(data.toolName).startsWith("clientmcp_")) this.complete(key);
11119
+ return;
11120
+ }
11121
+ if (event.eventType !== "tool_execution_start" || typeof data.toolName !== "string" || !data.toolName.startsWith("clientmcp_") || this.receipts.has(key) || this.pending.has(key)) return;
11122
+ const controller = new AbortController();
11123
+ this.pending.set(key, { controller, running: false, args: data.args ?? {}, context: {
11124
+ sessionId: this.sessionId,
11125
+ runId: event.runId,
11126
+ toolCallId: data.toolCallId,
11127
+ toolName: data.toolName,
11128
+ idempotencyKey: key,
11129
+ signal: AbortSignal.any([this.signal, controller.signal])
11130
+ } });
11131
+ }
11132
+ complete(key) {
11133
+ this.pending.get(key)?.controller.abort(new Error("Client MCP call completed"));
11134
+ this.pending.delete(key);
11135
+ this.receipts.add(key);
11136
+ while (this.receipts.size > receiptLimit) this.receipts.delete(this.receipts.values().next().value);
11137
+ if (this.options.storage) {
11138
+ try {
11139
+ this.options.storage.setItem(this.storageKey, JSON.stringify([...this.receipts]));
11140
+ } catch (error) {
11141
+ this.report(error);
11142
+ }
11143
+ }
11144
+ }
11145
+ dispatch() {
11146
+ if (!this.online || this.syncing || this.signal.aborted) return;
11147
+ for (const call of this.pending.values()) {
11148
+ if (call.running) continue;
11149
+ call.running = true;
11150
+ void this.execute(call).catch((error) => {
11151
+ if (!call.context.signal.aborted) this.report(error);
11152
+ });
11153
+ }
11154
+ }
11155
+ async execute(call) {
11156
+ const { context } = call;
11157
+ let result;
11158
+ const callback = this.callbacks.get(context.toolName);
11159
+ try {
11160
+ result = callback ? await callback.execute(call.args, context) : errorResult(`CLIENT_MCP_CALLBACK_NOT_REGISTERED: ${context.toolName}`);
11161
+ if (!result || !Array.isArray(result.content)) throw new Error("Callback must return an MCP result with a content array");
11162
+ result = JSON.parse(JSON.stringify(result));
11163
+ } catch (error) {
11164
+ if (context.signal.aborted) return;
11165
+ result = errorResult(`CLIENT_MCP_CALLBACK_ERROR: ${asError(error).message}`);
11166
+ }
11167
+ let failures = 0;
11168
+ let invalidResult = false;
11169
+ while (!context.signal.aborted) {
11170
+ try {
11171
+ await request2(this.api.submitAgentSessionClientMcpResult({ sessionId: this.sessionId, runId: context.runId, toolCallId: context.toolCallId, requestBody: result }), context.signal);
11172
+ this.complete(context.idempotencyKey);
11173
+ return;
11174
+ } catch (error) {
11175
+ if (context.signal.aborted) return;
11176
+ if (error instanceof BrazosdError && error.status === 409) {
11177
+ this.complete(context.idempotencyKey);
11178
+ return;
11179
+ }
11180
+ this.report(error);
11181
+ if (error instanceof BrazosdError && error.status === 400 && !invalidResult) {
11182
+ invalidResult = true;
11183
+ result = errorResult("CLIENT_MCP_INVALID_RESULT: the callback returned an invalid MCP result");
11184
+ continue;
11185
+ }
11186
+ if (error instanceof BrazosdError && error.status >= 400 && error.status < 500 && ![401, 408, 429].includes(error.status)) return;
11187
+ await delay(Math.min(500 * 2 ** Math.min(failures++, 6), 3e4), context.signal);
11188
+ }
11189
+ }
11190
+ }
11191
+ };
11192
+ var SubscriptionRejected = class extends Error {
11193
+ };
11194
+
11195
+ // src/client.ts
9577
11196
  var BrazosdClient = class {
9578
11197
  api;
9579
11198
  anclax;
9580
11199
  serverless;
11200
+ socketURL;
11201
+ signal;
9581
11202
  constructor(options = {}) {
9582
11203
  const context = {
9583
11204
  ...options,
9584
11205
  apiUrl: options.apiUrl ? apiURL(options.apiUrl) : void 0,
9585
- credentials: options.credentials ?? fileCredentials(options.credentialsFile)
11206
+ credentials: options.credentials ?? (() => {
11207
+ throw new Error("Provide a Brazosd credential provider");
11208
+ })
9586
11209
  };
9587
11210
  this.api = new ApiClient({}, createRequest(context, "api")).default;
9588
11211
  this.anclax = new AnclaxClient({}, createRequest(context, "anclax")).default;
9589
11212
  this.serverless = new ServerlessClient({}, createRequest(context, "serverless")).default;
11213
+ this.socketURL = () => realtimeURL(context);
11214
+ this.signal = options.signal;
11215
+ }
11216
+ clientMCP(sessionId, options = {}) {
11217
+ return new ClientMCPBridge(this.api, sessionId, this.socketURL, {
11218
+ ...options,
11219
+ signal: this.signal && options.signal ? AbortSignal.any([this.signal, options.signal]) : options.signal ?? this.signal
11220
+ });
11221
+ }
11222
+ };
11223
+
11224
+ // src/credentials.ts
11225
+ import { readFile } from "node:fs/promises";
11226
+ var DEFAULT_CREDENTIALS_FILE = "/run/brazosd/identity/credentials.json";
11227
+ function fileCredentials(path = DEFAULT_CREDENTIALS_FILE) {
11228
+ let cached;
11229
+ let cacheUntil = 0;
11230
+ let pending;
11231
+ return () => {
11232
+ if (cached && Date.now() < cacheUntil) return Promise.resolve(cached);
11233
+ if (!pending) {
11234
+ pending = readFile(path, "utf8").then((raw) => {
11235
+ const value = JSON.parse(raw);
11236
+ const expiresAt = Date.parse(value.expiresAt);
11237
+ if (typeof value.accessToken !== "string" || !value.accessToken || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
11238
+ throw new Error("Brazosd instance credentials are missing or expired");
11239
+ }
11240
+ cached = { accessToken: value.accessToken, apiUrl: value.apiUrl, expiresAt: value.expiresAt };
11241
+ cacheUntil = Math.min(Date.now() + 1e3, expiresAt);
11242
+ return cached;
11243
+ }).finally(() => {
11244
+ pending = void 0;
11245
+ });
11246
+ }
11247
+ return pending;
11248
+ };
11249
+ }
11250
+
11251
+ // src/sso.ts
11252
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
11253
+ import { join } from "node:path";
11254
+ import { homedir } from "node:os";
11255
+
11256
+ // src/sso-jwks.ts
11257
+ import { createPublicKey, verify } from "node:crypto";
11258
+ import { mkdir } from "node:fs/promises";
11259
+ import { dirname } from "node:path";
11260
+ var SQLiteSSOKeyCache = class {
11261
+ constructor(filename) {
11262
+ this.filename = filename;
11263
+ }
11264
+ filename;
11265
+ database;
11266
+ db() {
11267
+ return this.database ??= import("node:sqlite").then(async ({ DatabaseSync }) => {
11268
+ if (this.filename !== ":memory:") await mkdir(dirname(this.filename), { recursive: true, mode: 448 });
11269
+ const db = new DatabaseSync(this.filename);
11270
+ db.exec("PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS brazosd_sso_jwks (issuer TEXT PRIMARY KEY, payload TEXT NOT NULL)");
11271
+ return db;
11272
+ });
11273
+ }
11274
+ async get(issuer) {
11275
+ const row = (await this.db()).prepare("SELECT payload FROM brazosd_sso_jwks WHERE issuer=?").get(issuer);
11276
+ return row ? JSON.parse(String(row.payload)) : void 0;
11277
+ }
11278
+ async set(issuer, keys) {
11279
+ (await this.db()).prepare("INSERT INTO brazosd_sso_jwks(issuer,payload) VALUES(?,?) ON CONFLICT(issuer) DO UPDATE SET payload=excluded.payload").run(issuer, JSON.stringify(keys));
11280
+ }
11281
+ async close() {
11282
+ if (this.database) (await this.database).close();
11283
+ this.database = void 0;
11284
+ }
11285
+ };
11286
+ function decodePart(part) {
11287
+ if (!/^[A-Za-z0-9_-]+$/.test(part)) throw new Error("Invalid SSO JWT encoding");
11288
+ const raw = Buffer.from(part, "base64url");
11289
+ if (raw.toString("base64url") !== part) throw new Error("Invalid SSO JWT encoding");
11290
+ const value = JSON.parse(raw.toString("utf8"));
11291
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid SSO JWT object");
11292
+ return value;
11293
+ }
11294
+ var SSOIdentityVerifier = class {
11295
+ constructor(options) {
11296
+ this.options = options;
11297
+ const url = new URL(options.jwksUrl);
11298
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.hash) throw new Error("Invalid JWKS URL");
11299
+ }
11300
+ options;
11301
+ memory;
11302
+ loading;
11303
+ fetching;
11304
+ lastUnknownRefresh = 0;
11305
+ async download() {
11306
+ if (this.fetching) return this.fetching;
11307
+ const run = async () => {
11308
+ const response = await fetch(this.options.jwksUrl, { redirect: "error", signal: AbortSignal.timeout(1e4) });
11309
+ if (!response.ok) {
11310
+ await response.body?.cancel();
11311
+ throw new Error(`JWKS endpoint returned HTTP ${response.status}`);
11312
+ }
11313
+ const jwks = await response.json();
11314
+ if (!Array.isArray(jwks.keys) || jwks.keys.length > 100) throw new Error("Invalid JWKS response");
11315
+ const ids = /* @__PURE__ */ new Set();
11316
+ for (const key of jwks.keys) {
11317
+ if (key.kty !== "OKP" || key.crv !== "Ed25519" || key.alg !== "EdDSA" || key.use !== "sig" || typeof key.kid !== "string" || !key.kid || ids.has(key.kid) || !Number.isSafeInteger(key.exp) || typeof key.x !== "string" || Buffer.from(key.x, "base64url").length !== 32 || key.d !== void 0) {
11318
+ throw new Error("Invalid SSO signing key");
11319
+ }
11320
+ ids.add(key.kid);
11321
+ }
11322
+ const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(response.headers.get("cache-control") ?? "");
11323
+ const seconds = Math.min(maxAge ? Number(maxAge[1]) : 300, 3600);
11324
+ const keys = { keys: jwks.keys, freshUntil: Date.now() + seconds * 1e3 };
11325
+ await this.options.cache.set(this.cacheNamespace(), keys);
11326
+ this.memory = keys;
11327
+ return keys;
11328
+ };
11329
+ this.fetching = run();
11330
+ try {
11331
+ return await this.fetching;
11332
+ } finally {
11333
+ this.fetching = void 0;
11334
+ }
11335
+ }
11336
+ cacheNamespace() {
11337
+ return this.options.issuer + "\n" + new URL(this.options.jwksUrl).href;
11338
+ }
11339
+ async keys() {
11340
+ if (this.memory && this.memory.freshUntil > Date.now()) return this.memory;
11341
+ if (this.loading) return this.loading;
11342
+ this.loading = (async () => {
11343
+ const stored = await this.options.cache.get(this.cacheNamespace());
11344
+ if (stored && stored.freshUntil > Date.now()) return this.memory = stored;
11345
+ return this.download();
11346
+ })();
11347
+ try {
11348
+ return await this.loading;
11349
+ } finally {
11350
+ this.loading = void 0;
11351
+ }
11352
+ }
11353
+ async verify(token) {
11354
+ if (token.length > 16384) throw new Error("SSO JWT is too large");
11355
+ const parts = token.split(".");
11356
+ if (parts.length !== 3) throw new Error("Invalid SSO JWT");
11357
+ const header = decodePart(parts[0]);
11358
+ const claims = decodePart(parts[1]);
11359
+ if (header.alg !== "EdDSA" || header.typ !== "brazosd-sso+jwt" || typeof header.kid !== "string" || !header.kid || header.kid.length > 128 || header.crit !== void 0 || header.jku !== void 0 || header.jwk !== void 0 || header.x5u !== void 0) throw new Error("Invalid SSO JWT header");
11360
+ if (claims.iss !== this.options.issuer || claims.aud !== this.options.audience || claims.token_use !== "sso_identity") throw new Error("SSO JWT issuer, audience or purpose mismatch");
11361
+ const now = Math.floor(Date.now() / 1e3);
11362
+ if (![claims.account_id, claims.org_id, claims.user_id].every((id) => typeof id === "number" && Number.isSafeInteger(id) && id > 0) || claims.sub !== String(claims.account_id)) throw new Error("Invalid SSO identity");
11363
+ if (typeof claims.exp !== "number" || typeof claims.iat !== "number" || !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat) || claims.exp <= now || claims.iat > now + 30 || claims.exp <= claims.iat || claims.exp - claims.iat > 300 || claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isSafeInteger(claims.nbf) || claims.nbf > now + 30)) throw new Error("SSO JWT expired or has invalid timestamps");
11364
+ let set = await this.keys();
11365
+ let key = set.keys.find((item) => item.kid === header.kid);
11366
+ if (!key && (this.fetching || Date.now() - this.lastUnknownRefresh >= 5e3)) {
11367
+ this.lastUnknownRefresh = Date.now();
11368
+ set = await this.download();
11369
+ key = set.keys.find((item) => item.kid === header.kid);
11370
+ }
11371
+ if (!key || key.exp <= now || claims.exp > key.exp) throw new Error("Unknown or expired SSO signing key");
11372
+ const signature = Buffer.from(parts[2], "base64url");
11373
+ if (signature.length !== 64 || signature.toString("base64url") !== parts[2] || !verify(null, Buffer.from(parts[0] + "." + parts[1]), createPublicKey({ key, format: "jwk" }), signature)) throw new Error("Invalid SSO JWT signature");
11374
+ return claims;
11375
+ }
11376
+ };
11377
+
11378
+ // src/sso.ts
11379
+ function userTokens(tokens) {
11380
+ if (tokens.mode !== "org-user" || !tokens.accessToken || !tokens.refreshToken || !tokens.grantId || !tokens.refreshExpiresAt || tokens.identityToken) throw new Error("Organization-user SSO credentials required");
11381
+ }
11382
+ function sameSecret(a, b) {
11383
+ const x = Buffer.from(a), y = Buffer.from(b);
11384
+ return x.length === y.length && timingSafeEqual(x, y);
11385
+ }
11386
+ var BrazosdSSO = class {
11387
+ constructor(options) {
11388
+ this.options = options;
11389
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(options.appId)) throw new Error("Invalid SSO application ID");
11390
+ this.secret = Buffer.from(options.loginSecret, "base64url");
11391
+ if (this.secret.length !== 32 || this.secret.toString("base64url") !== options.loginSecret) throw new Error("SSO loginSecret must contain 32 random bytes encoded as base64url");
11392
+ const callback = new URL(options.redirectUri);
11393
+ this.secure = callback.protocol === "https:";
11394
+ if (!this.secure && !(callback.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(callback.hostname)) || callback.username || callback.password || callback.hash) throw new Error("SSO callback requires HTTPS, except for loopback development");
11395
+ this.cookiePrefix = (this.secure ? "__Host-" : "") + "brazosd_sso_" + options.appId + "_";
11396
+ this.service = createClient(options);
11397
+ this.verifier = new SSOIdentityVerifier({
11398
+ issuer: options.issuer ?? "https://brazosd.com",
11399
+ audience: options.appId,
11400
+ jwksUrl: options.jwksUrl ?? "https://api.brazosd.com/.well-known/jwks.json",
11401
+ cache: options.keyCache ?? new SQLiteSSOKeyCache(join(homedir(), ".cache", "brazosd-sso", "jwks.sqlite"))
11402
+ });
11403
+ }
11404
+ options;
11405
+ service;
11406
+ secret;
11407
+ cookiePrefix;
11408
+ secure;
11409
+ verifier;
11410
+ refreshing = /* @__PURE__ */ new Map();
11411
+ cookie(state, value, maxAge) {
11412
+ return `${this.cookiePrefix}${state}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${this.secure ? "; Secure" : ""}`;
11413
+ }
11414
+ aad() {
11415
+ return Buffer.from(`brazosd:sso:login:${this.options.appId}:${this.options.redirectUri}`);
11416
+ }
11417
+ seal(transaction) {
11418
+ const iv = randomBytes(12);
11419
+ const cipher = createCipheriv("aes-256-gcm", this.secret, iv);
11420
+ cipher.setAAD(this.aad());
11421
+ const payload = Buffer.concat([cipher.update(JSON.stringify(transaction)), cipher.final()]);
11422
+ return Buffer.concat([iv, cipher.getAuthTag(), payload]).toString("base64url");
11423
+ }
11424
+ open(value) {
11425
+ const data = Buffer.from(value, "base64url");
11426
+ if (data.length < 29 || data.length > 2048) throw new Error("Invalid SSO login cookie");
11427
+ const cipher = createDecipheriv("aes-256-gcm", this.secret, data.subarray(0, 12));
11428
+ cipher.setAAD(this.aad());
11429
+ cipher.setAuthTag(data.subarray(12, 28));
11430
+ return JSON.parse(Buffer.concat([cipher.update(data.subarray(28)), cipher.final()]).toString("utf8"));
11431
+ }
11432
+ /** Send setCookie and redirect to authorizationUrl. No service credential enters the URL. */
11433
+ async beginLogin(mode) {
11434
+ if (mode !== "identity" && mode !== "org-user") throw new Error("Invalid SSO mode");
11435
+ const state = randomBytes(32).toString("base64url");
11436
+ const verifier = randomBytes(32).toString("base64url");
11437
+ const request3 = await this.service.api.createSsoRequest({ requestBody: {
11438
+ appId: this.options.appId,
11439
+ redirectUri: this.options.redirectUri,
11440
+ mode,
11441
+ state,
11442
+ codeChallenge: createHash("sha256").update(verifier).digest("base64url")
11443
+ } });
11444
+ const authorization = new URL(mode === "org-user" ? "/sso/" : "/sso_jwt/", this.options.webUrl ?? "https://brazosd.com");
11445
+ if (!["http:", "https:"].includes(authorization.protocol) || authorization.username || authorization.password) throw new Error("Invalid SSO frontend URL");
11446
+ authorization.searchParams.set("request_id", request3.id);
11447
+ const expiresAt = Date.parse(request3.expiresAt);
11448
+ return { authorizationUrl: authorization.href, setCookie: this.cookie(state, this.seal({ state, verifier, mode, expiresAt }), Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3))) };
11449
+ }
11450
+ /** Call only on the registered callback. Persist returned tokens in the application's server-side session store. */
11451
+ async completeLogin(callbackUrl, cookieHeader) {
11452
+ const callback = new URL(callbackUrl);
11453
+ const registered = new URL(this.options.redirectUri);
11454
+ const state = callback.searchParams.get("state") ?? "";
11455
+ const code = callback.searchParams.get("code") ?? "";
11456
+ if (!/^[A-Za-z0-9_-]{43}$/.test(state) || callback.searchParams.getAll("state").length !== 1 || callback.searchParams.getAll("code").length !== 1) throw new Error("Invalid SSO callback");
11457
+ callback.searchParams.delete("state");
11458
+ callback.searchParams.delete("code");
11459
+ callback.searchParams.sort();
11460
+ registered.searchParams.sort();
11461
+ if (callback.href !== registered.href) throw new Error("SSO callback URL mismatch");
11462
+ const name = this.cookiePrefix + state;
11463
+ const values = cookieHeader.split(";").map((item) => item.trim()).filter((item) => item.startsWith(name + "="));
11464
+ if (values.length !== 1) throw new Error("SSO login cookie is missing or ambiguous");
11465
+ let transaction;
11466
+ try {
11467
+ transaction = this.open(values[0].slice(name.length + 1));
11468
+ } catch {
11469
+ throw new Error("Invalid SSO login cookie");
11470
+ }
11471
+ if (typeof transaction.state !== "string" || !sameSecret(state, transaction.state) || !(transaction.expiresAt > Date.now()) || !["org-user", "identity"].includes(transaction.mode)) throw new Error("SSO login expired or state mismatch");
11472
+ const tokens = await this.service.api.exchangeSsoCode({ requestBody: { appId: this.options.appId, code, redirectUri: this.options.redirectUri, codeVerifier: transaction.verifier } });
11473
+ if (tokens.mode !== transaction.mode) throw new Error("SSO response mode mismatch");
11474
+ const clearCookie = this.cookie(state, "", 0);
11475
+ if (tokens.mode === "org-user") {
11476
+ userTokens(tokens);
11477
+ return { tokens, clearCookie };
11478
+ }
11479
+ if (!tokens.identityToken || tokens.accessToken || tokens.refreshToken) throw new Error("Invalid SSO identity response");
11480
+ const identity = await this.verifyIdentityToken(tokens.identityToken);
11481
+ if (identity.account_id !== tokens.accountId || identity.org_id !== tokens.orgId || identity.user_id !== tokens.userId) throw new Error("SSO identity response mismatch");
11482
+ return { tokens, identity, clearCookie };
11483
+ }
11484
+ verifyIdentityToken(token) {
11485
+ return this.verifier.verify(token);
11486
+ }
11487
+ /** Concurrent instances derive the same retry ID from the same refresh credential. */
11488
+ async refresh(tokens) {
11489
+ userTokens(tokens);
11490
+ if (!(Date.parse(tokens.refreshExpiresAt) > Date.now())) throw new Error("SSO grant expired; log in again");
11491
+ const id = createHash("sha256").update("brazosd-sso-refresh\0" + tokens.refreshToken).digest().subarray(0, 16);
11492
+ id[6] = id[6] & 15 | 64;
11493
+ id[8] = id[8] & 63 | 128;
11494
+ const hex = id.toString("hex");
11495
+ const requestId = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
11496
+ let pending = this.refreshing.get(requestId);
11497
+ if (!pending) {
11498
+ pending = this.service.api.refreshSsoTokens({ requestBody: { appId: this.options.appId, refreshToken: tokens.refreshToken, requestId } }).then((next) => {
11499
+ userTokens(next);
11500
+ if (next.grantId !== tokens.grantId || next.accountId !== tokens.accountId || next.orgId !== tokens.orgId || next.userId !== tokens.userId) throw new Error("SSO refresh identity mismatch");
11501
+ return next;
11502
+ });
11503
+ this.refreshing.set(requestId, pending);
11504
+ }
11505
+ try {
11506
+ return await pending;
11507
+ } finally {
11508
+ if (this.refreshing.get(requestId) === pending) this.refreshing.delete(requestId);
11509
+ }
11510
+ }
11511
+ /** saveTokens must compare-and-swap using expectedRefreshToken when sessions are shared. */
11512
+ userClient(session) {
11513
+ const serviceCredentials = this.options.credentials ?? fileCredentials(this.options.credentialsFile);
11514
+ return createClient({ apiUrl: this.options.apiUrl, credentials: async () => {
11515
+ let tokens = await session.getTokens();
11516
+ userTokens(tokens);
11517
+ if (!(Date.parse(tokens.expiresAt) > Date.now() + 3e4)) {
11518
+ const next = await this.refresh(tokens);
11519
+ await session.saveTokens(next, tokens.refreshToken);
11520
+ tokens = await session.getTokens();
11521
+ userTokens(tokens);
11522
+ }
11523
+ return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, apiUrl: this.options.apiUrl ?? (await serviceCredentials()).apiUrl };
11524
+ } });
11525
+ }
11526
+ /** Also delete the application's own session/cookie after revoking this grant. */
11527
+ async revoke(tokens) {
11528
+ userTokens(tokens);
11529
+ await this.service.api.revokeSsoGrant({ grantId: tokens.grantId });
11530
+ }
11531
+ };
11532
+ function createSSO(options) {
11533
+ return new BrazosdSSO(options);
11534
+ }
11535
+
11536
+ // src/index.ts
11537
+ var BrazosdClient2 = class extends BrazosdClient {
11538
+ constructor(options = {}) {
11539
+ super({ ...options, credentials: options.credentials ?? fileCredentials(options.credentialsFile) });
9590
11540
  }
9591
11541
  };
9592
11542
  function createClient(options) {
9593
- return new BrazosdClient(options);
11543
+ return new BrazosdClient2(options);
9594
11544
  }
9595
11545
  export {
9596
- BrazosdClient,
11546
+ BrazosdClient2 as BrazosdClient,
9597
11547
  BrazosdError,
11548
+ BrazosdSSO,
9598
11549
  CancelError,
9599
11550
  CancelablePromise,
11551
+ ClientMCPBridge,
9600
11552
  DEFAULT_CREDENTIALS_FILE,
11553
+ SQLiteSSOKeyCache,
11554
+ SSOIdentityVerifier,
9601
11555
  createClient,
11556
+ createSSO,
9602
11557
  fileCredentials
9603
11558
  };