@atbash/sdk 0.14.1-dev.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -33,11 +33,11 @@ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__
33
33
  mod2
34
34
  ));
35
35
 
36
- // <define:__ATBASH_CHROMIA_NODE_URLS__>
37
- var define_ATBASH_CHROMIA_NODE_URLS_default;
38
- var init_define_ATBASH_CHROMIA_NODE_URLS = __esm({
39
- "<define:__ATBASH_CHROMIA_NODE_URLS__>"() {
40
- define_ATBASH_CHROMIA_NODE_URLS_default = ["https://node0.testnet.chromia.com:7740", "https://node1.testnet.chromia.com:7740"];
36
+ // <define:__ATBASH_DEV_JUDGE_PINS__>
37
+ var define_ATBASH_DEV_JUDGE_PINS_default;
38
+ var init_define_ATBASH_DEV_JUDGE_PINS = __esm({
39
+ "<define:__ATBASH_DEV_JUDGE_PINS__>"() {
40
+ define_ATBASH_DEV_JUDGE_PINS_default = ["03f1632c850eb126edf64923484a21713d3b3931a0755258a2cb6090d4a1859d3a"];
41
41
  }
42
42
  });
43
43
 
@@ -49,12 +49,21 @@ var init_define_ATBASH_PRIVATE_NODE_URLS = __esm({
49
49
  }
50
50
  });
51
51
 
52
+ // <define:__ATBASH_PROD_JUDGE_PINS__>
53
+ var define_ATBASH_PROD_JUDGE_PINS_default;
54
+ var init_define_ATBASH_PROD_JUDGE_PINS = __esm({
55
+ "<define:__ATBASH_PROD_JUDGE_PINS__>"() {
56
+ define_ATBASH_PROD_JUDGE_PINS_default = ["02818eced310b32f227fada6dba76dbf0f9171265f63ec9860cc5a89a2bdb18bff"];
57
+ }
58
+ });
59
+
52
60
  // (disabled):node_modules/buffer/index.js
53
61
  var require_buffer = __commonJS({
54
62
  "(disabled):node_modules/buffer/index.js"() {
55
63
  "use strict";
56
- init_define_ATBASH_CHROMIA_NODE_URLS();
64
+ init_define_ATBASH_DEV_JUDGE_PINS();
57
65
  init_define_ATBASH_PRIVATE_NODE_URLS();
66
+ init_define_ATBASH_PROD_JUDGE_PINS();
58
67
  }
59
68
  });
60
69
 
@@ -62,8 +71,9 @@ var require_buffer = __commonJS({
62
71
  var require_bn = __commonJS({
63
72
  "node_modules/bn.js/lib/bn.js"(exports, module) {
64
73
  "use strict";
65
- init_define_ATBASH_CHROMIA_NODE_URLS();
74
+ init_define_ATBASH_DEV_JUDGE_PINS();
66
75
  init_define_ATBASH_PRIVATE_NODE_URLS();
76
+ init_define_ATBASH_PROD_JUDGE_PINS();
67
77
  (function(module2, exports2) {
68
78
  "use strict";
69
79
  function assert2(val, msg) {
@@ -2882,28 +2892,34 @@ var require_bn = __commonJS({
2882
2892
  });
2883
2893
 
2884
2894
  // src-ts/index.ts
2885
- init_define_ATBASH_CHROMIA_NODE_URLS();
2895
+ init_define_ATBASH_DEV_JUDGE_PINS();
2886
2896
  init_define_ATBASH_PRIVATE_NODE_URLS();
2897
+ init_define_ATBASH_PROD_JUDGE_PINS();
2887
2898
 
2888
2899
  // src-ts/browser/native.ts
2889
- init_define_ATBASH_CHROMIA_NODE_URLS();
2900
+ init_define_ATBASH_DEV_JUDGE_PINS();
2890
2901
  init_define_ATBASH_PRIVATE_NODE_URLS();
2902
+ init_define_ATBASH_PROD_JUDGE_PINS();
2891
2903
 
2892
2904
  // node_modules/@noble/curves/secp256k1.js
2893
- init_define_ATBASH_CHROMIA_NODE_URLS();
2905
+ init_define_ATBASH_DEV_JUDGE_PINS();
2894
2906
  init_define_ATBASH_PRIVATE_NODE_URLS();
2907
+ init_define_ATBASH_PROD_JUDGE_PINS();
2895
2908
 
2896
2909
  // node_modules/@noble/hashes/sha2.js
2897
- init_define_ATBASH_CHROMIA_NODE_URLS();
2910
+ init_define_ATBASH_DEV_JUDGE_PINS();
2898
2911
  init_define_ATBASH_PRIVATE_NODE_URLS();
2912
+ init_define_ATBASH_PROD_JUDGE_PINS();
2899
2913
 
2900
2914
  // node_modules/@noble/hashes/_md.js
2901
- init_define_ATBASH_CHROMIA_NODE_URLS();
2915
+ init_define_ATBASH_DEV_JUDGE_PINS();
2902
2916
  init_define_ATBASH_PRIVATE_NODE_URLS();
2917
+ init_define_ATBASH_PROD_JUDGE_PINS();
2903
2918
 
2904
2919
  // node_modules/@noble/hashes/utils.js
2905
- init_define_ATBASH_CHROMIA_NODE_URLS();
2920
+ init_define_ATBASH_DEV_JUDGE_PINS();
2906
2921
  init_define_ATBASH_PRIVATE_NODE_URLS();
2922
+ init_define_ATBASH_PROD_JUDGE_PINS();
2907
2923
  function isBytes(a) {
2908
2924
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2909
2925
  }
@@ -3325,12 +3341,14 @@ var sha256 = /* @__PURE__ */ createHasher(
3325
3341
  );
3326
3342
 
3327
3343
  // node_modules/@noble/curves/abstract/curve.js
3328
- init_define_ATBASH_CHROMIA_NODE_URLS();
3344
+ init_define_ATBASH_DEV_JUDGE_PINS();
3329
3345
  init_define_ATBASH_PRIVATE_NODE_URLS();
3346
+ init_define_ATBASH_PROD_JUDGE_PINS();
3330
3347
 
3331
3348
  // node_modules/@noble/curves/utils.js
3332
- init_define_ATBASH_CHROMIA_NODE_URLS();
3349
+ init_define_ATBASH_DEV_JUDGE_PINS();
3333
3350
  init_define_ATBASH_PRIVATE_NODE_URLS();
3351
+ init_define_ATBASH_PROD_JUDGE_PINS();
3334
3352
  var abytes2 = (value, length, title) => abytes(value, length, title);
3335
3353
  var anumber2 = anumber;
3336
3354
  var bytesToHex2 = bytesToHex;
@@ -3483,8 +3501,9 @@ function validateObject(object, fields = {}, optFields = {}) {
3483
3501
  }
3484
3502
 
3485
3503
  // node_modules/@noble/curves/abstract/modular.js
3486
- init_define_ATBASH_CHROMIA_NODE_URLS();
3504
+ init_define_ATBASH_DEV_JUDGE_PINS();
3487
3505
  init_define_ATBASH_PRIVATE_NODE_URLS();
3506
+ init_define_ATBASH_PROD_JUDGE_PINS();
3488
3507
  var _0n2 = /* @__PURE__ */ BigInt(0);
3489
3508
  var _1n2 = /* @__PURE__ */ BigInt(1);
3490
3509
  var _2n = /* @__PURE__ */ BigInt(2);
@@ -4133,12 +4152,14 @@ function createKeygen(randomSecretKey, getPublicKey) {
4133
4152
  }
4134
4153
 
4135
4154
  // node_modules/@noble/curves/abstract/weierstrass.js
4136
- init_define_ATBASH_CHROMIA_NODE_URLS();
4155
+ init_define_ATBASH_DEV_JUDGE_PINS();
4137
4156
  init_define_ATBASH_PRIVATE_NODE_URLS();
4157
+ init_define_ATBASH_PROD_JUDGE_PINS();
4138
4158
 
4139
4159
  // node_modules/@noble/hashes/hmac.js
4140
- init_define_ATBASH_CHROMIA_NODE_URLS();
4160
+ init_define_ATBASH_DEV_JUDGE_PINS();
4141
4161
  init_define_ATBASH_PRIVATE_NODE_URLS();
4162
+ init_define_ATBASH_PROD_JUDGE_PINS();
4142
4163
  var _HMAC = class {
4143
4164
  oHash;
4144
4165
  iHash;
@@ -5170,8 +5191,9 @@ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
5170
5191
  var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
5171
5192
 
5172
5193
  // node_modules/postchain-client/built/esm/index.js
5173
- init_define_ATBASH_CHROMIA_NODE_URLS();
5194
+ init_define_ATBASH_DEV_JUDGE_PINS();
5174
5195
  init_define_ATBASH_PRIVATE_NODE_URLS();
5196
+ init_define_ATBASH_PROD_JUDGE_PINS();
5175
5197
  var import_bn = __toESM(require_bn(), 1);
5176
5198
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
5177
5199
  function getDefaultExportFromCjs(x) {
@@ -10054,8 +10076,8 @@ Reporter$3.prototype.wrapResult = function wrapResult(result) {
10054
10076
  errors: state2.errors
10055
10077
  };
10056
10078
  };
10057
- function ReporterError$1(path4, msg) {
10058
- this.path = path4;
10079
+ function ReporterError$1(path3, msg) {
10080
+ this.path = path3;
10059
10081
  this.rethrow(msg);
10060
10082
  }
10061
10083
  inherits$v(ReporterError$1, Error);
@@ -12126,7 +12148,7 @@ function requireBuffer_list() {
12126
12148
  }
12127
12149
  }, {
12128
12150
  key: "join",
12129
- value: function join3(s2) {
12151
+ value: function join2(s2) {
12130
12152
  if (this.length === 0) return "";
12131
12153
  var p = this.head;
12132
12154
  var ret = "" + p.data;
@@ -16208,7 +16230,7 @@ function requireBufferList() {
16208
16230
  this.head = this.tail = null;
16209
16231
  this.length = 0;
16210
16232
  };
16211
- BufferList2.prototype.join = function join3(s2) {
16233
+ BufferList2.prototype.join = function join2(s2) {
16212
16234
  if (this.length === 0) return "";
16213
16235
  var p = this.head;
16214
16236
  var ret = "" + p.data;
@@ -21769,23 +21791,23 @@ Splitter$1.prototype.flush = function() {
21769
21791
  return Buffer$9.concat([this.cache, padBuff]);
21770
21792
  };
21771
21793
  function createCipheriv$1(suite, password, iv) {
21772
- var config2 = MODES$1[suite.toLowerCase()];
21773
- if (!config2) throw new TypeError("invalid suite type");
21794
+ var config3 = MODES$1[suite.toLowerCase()];
21795
+ if (!config3) throw new TypeError("invalid suite type");
21774
21796
  if (typeof password === "string") password = Buffer$9.from(password);
21775
- if (password.length !== config2.key / 8) throw new TypeError("invalid key length " + password.length);
21797
+ if (password.length !== config3.key / 8) throw new TypeError("invalid key length " + password.length);
21776
21798
  if (typeof iv === "string") iv = Buffer$9.from(iv);
21777
- if (config2.mode !== "GCM" && iv.length !== config2.iv) throw new TypeError("invalid iv length " + iv.length);
21778
- if (config2.type === "stream") {
21779
- return new StreamCipher$1(config2.module, password, iv);
21780
- } else if (config2.type === "auth") {
21781
- return new AuthCipher$1(config2.module, password, iv);
21799
+ if (config3.mode !== "GCM" && iv.length !== config3.iv) throw new TypeError("invalid iv length " + iv.length);
21800
+ if (config3.type === "stream") {
21801
+ return new StreamCipher$1(config3.module, password, iv);
21802
+ } else if (config3.type === "auth") {
21803
+ return new AuthCipher$1(config3.module, password, iv);
21782
21804
  }
21783
- return new Cipher(config2.module, password, iv);
21805
+ return new Cipher(config3.module, password, iv);
21784
21806
  }
21785
21807
  function createCipher$1(suite, password) {
21786
- var config2 = MODES$1[suite.toLowerCase()];
21787
- if (!config2) throw new TypeError("invalid suite type");
21788
- var keys2 = ebtk$2(password, false, config2.key, config2.iv);
21808
+ var config3 = MODES$1[suite.toLowerCase()];
21809
+ if (!config3) throw new TypeError("invalid suite type");
21810
+ var keys2 = ebtk$2(password, false, config3.key, config3.iv);
21789
21811
  return createCipheriv$1(suite, keys2.key, keys2.iv);
21790
21812
  }
21791
21813
  encrypter.createCipheriv = createCipheriv$1;
@@ -21873,23 +21895,23 @@ function unpad(last) {
21873
21895
  return last.slice(0, 16 - padded);
21874
21896
  }
21875
21897
  function createDecipheriv$1(suite, password, iv) {
21876
- var config2 = MODES[suite.toLowerCase()];
21877
- if (!config2) throw new TypeError("invalid suite type");
21898
+ var config3 = MODES[suite.toLowerCase()];
21899
+ if (!config3) throw new TypeError("invalid suite type");
21878
21900
  if (typeof iv === "string") iv = Buffer$8.from(iv);
21879
- if (config2.mode !== "GCM" && iv.length !== config2.iv) throw new TypeError("invalid iv length " + iv.length);
21901
+ if (config3.mode !== "GCM" && iv.length !== config3.iv) throw new TypeError("invalid iv length " + iv.length);
21880
21902
  if (typeof password === "string") password = Buffer$8.from(password);
21881
- if (password.length !== config2.key / 8) throw new TypeError("invalid key length " + password.length);
21882
- if (config2.type === "stream") {
21883
- return new StreamCipher(config2.module, password, iv, true);
21884
- } else if (config2.type === "auth") {
21885
- return new AuthCipher(config2.module, password, iv, true);
21903
+ if (password.length !== config3.key / 8) throw new TypeError("invalid key length " + password.length);
21904
+ if (config3.type === "stream") {
21905
+ return new StreamCipher(config3.module, password, iv, true);
21906
+ } else if (config3.type === "auth") {
21907
+ return new AuthCipher(config3.module, password, iv, true);
21886
21908
  }
21887
- return new Decipher(config2.module, password, iv);
21909
+ return new Decipher(config3.module, password, iv);
21888
21910
  }
21889
21911
  function createDecipher$1(suite, password) {
21890
- var config2 = MODES[suite.toLowerCase()];
21891
- if (!config2) throw new TypeError("invalid suite type");
21892
- var keys2 = ebtk$1(password, false, config2.key, config2.iv);
21912
+ var config3 = MODES[suite.toLowerCase()];
21913
+ if (!config3) throw new TypeError("invalid suite type");
21914
+ var keys2 = ebtk$1(password, false, config3.key, config3.iv);
21893
21915
  return createDecipheriv$1(suite, keys2.key, keys2.iv);
21894
21916
  }
21895
21917
  decrypter.createDecipher = createDecipher$1;
@@ -30276,8 +30298,8 @@ Reporter.prototype.wrapResult = function wrapResult2(result) {
30276
30298
  errors: state2.errors
30277
30299
  };
30278
30300
  };
30279
- function ReporterError(path4, msg) {
30280
- this.path = path4;
30301
+ function ReporterError(path3, msg) {
30302
+ this.path = path3;
30281
30303
  this.rethrow(msg);
30282
30304
  }
30283
30305
  inherits(ReporterError, Error);
@@ -30372,7 +30394,7 @@ function requireBuffer() {
30372
30394
  }
30373
30395
  }
30374
30396
  buffer.EncoderBuffer = EncoderBuffer2;
30375
- EncoderBuffer2.prototype.join = function join3(out, offset) {
30397
+ EncoderBuffer2.prototype.join = function join2(out, offset) {
30376
30398
  if (!out)
30377
30399
  out = new Buffer5(this.length);
30378
30400
  if (!offset)
@@ -33307,8 +33329,8 @@ var parseUtil = {};
33307
33329
  const errors_js_12 = errors$3;
33308
33330
  const en_js_12 = __importDefault2(en);
33309
33331
  const makeIssue = (params) => {
33310
- const { data, path: path4, errorMaps, issueData } = params;
33311
- const fullPath = [...path4, ...issueData.path || []];
33332
+ const { data, path: path3, errorMaps, issueData } = params;
33333
+ const fullPath = [...path3, ...issueData.path || []];
33312
33334
  const fullIssue = {
33313
33335
  ...issueData,
33314
33336
  path: fullPath
@@ -33445,11 +33467,11 @@ var errorUtil_js_1 = errorUtil$1;
33445
33467
  var parseUtil_js_1 = parseUtil;
33446
33468
  var util_js_1 = util;
33447
33469
  var ParseInputLazyPath = class {
33448
- constructor(parent, value, path4, key3) {
33470
+ constructor(parent, value, path3, key3) {
33449
33471
  this._cachedPath = [];
33450
33472
  this.parent = parent;
33451
33473
  this.data = value;
33452
- this._path = path4;
33474
+ this._path = path3;
33453
33475
  this._key = key3;
33454
33476
  }
33455
33477
  get path() {
@@ -40355,21 +40377,21 @@ function createTimeoutController(timeout) {
40355
40377
  const timeoutId = setTimeout(() => controller.abort(timeoutError), timeout);
40356
40378
  return { controller, timeoutId };
40357
40379
  }
40358
- function handleRequest(method, path4, endpoint, timeout, postObject) {
40380
+ function handleRequest(method, path3, endpoint, timeout, postObject) {
40359
40381
  return __awaiter$2(this, void 0, void 0, function* () {
40360
40382
  if (method == enums_1$2.Method.GET) {
40361
- return yield get(path4, endpoint, timeout);
40383
+ return yield get(path3, endpoint, timeout);
40362
40384
  } else {
40363
- return yield post(path4, endpoint, timeout, postObject);
40385
+ return yield post(path3, endpoint, timeout, postObject);
40364
40386
  }
40365
40387
  });
40366
40388
  }
40367
- function get(path4, endpoint, timeout) {
40389
+ function get(path3, endpoint, timeout) {
40368
40390
  return __awaiter$2(this, void 0, void 0, function* () {
40369
- logger.debug(`GET URL ${new URL(path4, endpoint).href}`);
40391
+ logger.debug(`GET URL ${new URL(path3, endpoint).href}`);
40370
40392
  try {
40371
40393
  const { controller, timeoutId } = createTimeoutController(timeout);
40372
- const response = yield fetch(new URL(path4, endpoint).href, {
40394
+ const response = yield fetch(new URL(path3, endpoint).href, {
40373
40395
  signal: controller === null || controller === void 0 ? void 0 : controller.signal
40374
40396
  });
40375
40397
  if (timeoutId)
@@ -40407,9 +40429,9 @@ function constructBufferResponseBody(response) {
40407
40429
  return responseText ? responseText : response.statusText;
40408
40430
  });
40409
40431
  }
40410
- function post(path4, endpoint, timeout, requestBody) {
40432
+ function post(path3, endpoint, timeout, requestBody) {
40411
40433
  return __awaiter$2(this, void 0, void 0, function* () {
40412
- logger.debug(`POST URL ${new URL(path4, endpoint).href}`);
40434
+ logger.debug(`POST URL ${new URL(path3, endpoint).href}`);
40413
40435
  logger.debug(`POST body ${JSON.stringify(requestBody)}`);
40414
40436
  if (buffer_1.Buffer.isBuffer(requestBody)) {
40415
40437
  try {
@@ -40423,7 +40445,7 @@ function post(path4, endpoint, timeout, requestBody) {
40423
40445
  },
40424
40446
  signal: controller === null || controller === void 0 ? void 0 : controller.signal
40425
40447
  };
40426
- const response = yield fetch(new URL(path4, endpoint).href, requestOptions);
40448
+ const response = yield fetch(new URL(path3, endpoint).href, requestOptions);
40427
40449
  if (timeoutId)
40428
40450
  clearTimeout(timeoutId);
40429
40451
  const transactionTimestamp = response.headers.get("X-Transaction-Timestamp");
@@ -40434,7 +40456,7 @@ function post(path4, endpoint, timeout, requestBody) {
40434
40456
  } else {
40435
40457
  try {
40436
40458
  const { controller, timeoutId } = createTimeoutController(timeout);
40437
- const response = yield fetch(new URL(path4, endpoint).href, {
40459
+ const response = yield fetch(new URL(path3, endpoint).href, {
40438
40460
  method: "post",
40439
40461
  body: JSON.stringify(requestBody),
40440
40462
  headers: {
@@ -40585,7 +40607,7 @@ function requireFailoverStrategies() {
40585
40607
  exports.createTimeoutPromise = createTimeoutPromise;
40586
40608
  const utils_12 = requireUtils$1();
40587
40609
  const httpUtil_1 = httpUtil;
40588
- const logger2 = __importStar2(logger$3);
40610
+ const logger3 = __importStar2(logger$3);
40589
40611
  const http_utils_1 = httpUtils;
40590
40612
  function getUnreachableDuration(statusCode, error4) {
40591
40613
  if ((0, http_utils_1.isNetworkError)(error4)) {
@@ -40614,29 +40636,29 @@ function requireFailoverStrategies() {
40614
40636
  }
40615
40637
  }
40616
40638
  function abortOnError(_a2) {
40617
- return __awaiter2(this, arguments, void 0, function* ({ method, path: path4, config: config2, postObject, timeoutOverride }) {
40639
+ return __awaiter2(this, arguments, void 0, function* ({ method, path: path3, config: config3, postObject, timeoutOverride }) {
40618
40640
  return yield retryRequest({
40619
40641
  method,
40620
- path: path4,
40621
- config: config2,
40642
+ path: path3,
40643
+ config: config3,
40622
40644
  postObject,
40623
40645
  timeoutOverride,
40624
40646
  useNextNodeOnError: false,
40625
- recoveryThreshold: config2.recoveryThreshold
40647
+ recoveryThreshold: config3.recoveryThreshold
40626
40648
  // Use user config or let nodeManager use default
40627
40649
  });
40628
40650
  });
40629
40651
  }
40630
40652
  function tryNextOnError(_a2) {
40631
- return __awaiter2(this, arguments, void 0, function* ({ method, path: path4, config: config2, postObject, timeoutOverride }) {
40653
+ return __awaiter2(this, arguments, void 0, function* ({ method, path: path3, config: config3, postObject, timeoutOverride }) {
40632
40654
  return yield retryRequest({
40633
40655
  method,
40634
- path: path4,
40635
- config: config2,
40656
+ path: path3,
40657
+ config: config3,
40636
40658
  postObject,
40637
40659
  timeoutOverride,
40638
40660
  useNextNodeOnError: true,
40639
- recoveryThreshold: config2.recoveryThreshold
40661
+ recoveryThreshold: config3.recoveryThreshold
40640
40662
  });
40641
40663
  });
40642
40664
  }
@@ -40647,18 +40669,18 @@ function requireFailoverStrategies() {
40647
40669
  return endpointPoolLength - (endpointPoolLength - 1) / 3;
40648
40670
  }
40649
40671
  function queryMajority(_a2) {
40650
- return __awaiter2(this, arguments, void 0, function* ({ method, path: path4, config: config2, postObject, timeoutOverride }) {
40672
+ return __awaiter2(this, arguments, void 0, function* ({ method, path: path3, config: config3, postObject, timeoutOverride }) {
40651
40673
  var _b;
40652
- const bftMajorityThreshold = calculateBftMajorityThreshold(config2.endpointPool.length);
40653
- const failureThreshold = config2.endpointPool.length - bftMajorityThreshold + 1;
40654
- const { nodeManager: nodeManager2 } = config2;
40674
+ const bftMajorityThreshold = calculateBftMajorityThreshold(config3.endpointPool.length);
40675
+ const failureThreshold = config3.endpointPool.length - bftMajorityThreshold + 1;
40676
+ const { nodeManager: nodeManager2 } = config3;
40655
40677
  const timeout = 15e3;
40656
- const availableNodes = nodeManager2.getAvailableNodes((_b = config2.recoveryThreshold) !== null && _b !== void 0 ? _b : bftMajorityThreshold);
40678
+ const availableNodes = nodeManager2.getAvailableNodes((_b = config3.recoveryThreshold) !== null && _b !== void 0 ? _b : bftMajorityThreshold);
40657
40679
  const outcomes = [];
40658
40680
  const promises = availableNodes.map((node2) => __awaiter2(this, void 0, void 0, function* () {
40659
40681
  try {
40660
- const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config2.responseTimeout;
40661
- const response = yield (0, httpUtil_1.handleRequest)(method, path4, node2.url, requestTimeout, postObject);
40682
+ const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config3.responseTimeout;
40683
+ const response = yield (0, httpUtil_1.handleRequest)(method, path3, node2.url, requestTimeout, postObject);
40662
40684
  const { statusCode } = response;
40663
40685
  if (statusCode && (0, http_utils_1.isSuccessfulStatusCode)(statusCode)) {
40664
40686
  outcomes.push({ type: "SUCCESS", result: response });
@@ -40686,7 +40708,7 @@ function requireFailoverStrategies() {
40686
40708
  while (true) {
40687
40709
  if (groupedSuccessfulResponses.maxNumberOfEqualResponses() >= bftMajorityThreshold) {
40688
40710
  if (groupedSuccessfulResponses.numberOfDistinctResponses() > 1) {
40689
- logger2.warning(`Got disagreeing responses, but could still reach BFT majority`);
40711
+ logger3.warning(`Got disagreeing responses, but could still reach BFT majority`);
40690
40712
  }
40691
40713
  return groupedSuccessfulResponses.majorityResponse();
40692
40714
  }
@@ -40697,7 +40719,7 @@ function requireFailoverStrategies() {
40697
40719
  throw errorOutcomes[0].result;
40698
40720
  }
40699
40721
  }
40700
- if (outcomes.length >= config2.endpointPool.length) {
40722
+ if (outcomes.length >= config3.endpointPool.length) {
40701
40723
  throw new Error(exports.errorMessages.NO_CONSENSUS);
40702
40724
  }
40703
40725
  remainingPromises = yield racePromisesWithTimeout(remainingPromises, timeout);
@@ -40705,18 +40727,18 @@ function requireFailoverStrategies() {
40705
40727
  });
40706
40728
  }
40707
40729
  function singleEndpoint(_a2) {
40708
- return __awaiter2(this, arguments, void 0, function* ({ method, path: path4, config: config2, postObject, timeoutOverride }) {
40730
+ return __awaiter2(this, arguments, void 0, function* ({ method, path: path3, config: config3, postObject, timeoutOverride }) {
40709
40731
  let statusCode = null;
40710
40732
  let rspBody = null;
40711
40733
  let error4 = null;
40712
40734
  let transactionTimestamp = void 0;
40713
- const endpoint = config2.nodeManager.getNode();
40735
+ const endpoint = config3.nodeManager.getNode();
40714
40736
  if (!endpoint) {
40715
40737
  throw new Error("No nodes available after recovery attempt. Check node configuration.");
40716
40738
  }
40717
- for (let attempt = 0; attempt < config2.attemptsPerEndpoint; attempt++) {
40718
- const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config2.responseTimeout;
40719
- const response = yield (0, httpUtil_1.handleRequest)(method, path4, endpoint.url, requestTimeout, postObject);
40739
+ for (let attempt = 0; attempt < config3.attemptsPerEndpoint; attempt++) {
40740
+ const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config3.responseTimeout;
40741
+ const response = yield (0, httpUtil_1.handleRequest)(method, path3, endpoint.url, requestTimeout, postObject);
40720
40742
  if (response) {
40721
40743
  ({ error: error4, statusCode, rspBody, transactionTimestamp } = response);
40722
40744
  }
@@ -40724,25 +40746,25 @@ function requireFailoverStrategies() {
40724
40746
  if (!isError4 && !error4) {
40725
40747
  return { error: error4, statusCode, rspBody, transactionTimestamp };
40726
40748
  }
40727
- logger2.info(`${method} request failed on ${endpoint.url}. Attempt: ${attempt + 1} / ${config2.attemptsPerEndpoint}`);
40728
- yield (0, utils_12.sleep)(config2.attemptInterval);
40749
+ logger3.info(`${method} request failed on ${endpoint.url}. Attempt: ${attempt + 1} / ${config3.attemptsPerEndpoint}`);
40750
+ yield (0, utils_12.sleep)(config3.attemptInterval);
40729
40751
  }
40730
40752
  return { error: error4, statusCode, rspBody, transactionTimestamp };
40731
40753
  });
40732
40754
  }
40733
40755
  function retryRequest(_a2) {
40734
- return __awaiter2(this, arguments, void 0, function* ({ method, path: path4, config: config2, postObject, useNextNodeOnError, recoveryThreshold, timeoutOverride }) {
40756
+ return __awaiter2(this, arguments, void 0, function* ({ method, path: path3, config: config3, postObject, useNextNodeOnError, recoveryThreshold, timeoutOverride }) {
40735
40757
  var _b, _c, _d;
40736
40758
  let statusCode = null;
40737
40759
  let rspBody = null;
40738
40760
  let error4 = null;
40739
40761
  let transactionTimestamp = void 0;
40740
- const { nodeManager: nodeManager2 } = config2;
40762
+ const { nodeManager: nodeManager2 } = config3;
40741
40763
  const availableNodes = nodeManager2.getAvailableNodes(recoveryThreshold);
40742
40764
  for (const node2 of availableNodes) {
40743
- for (let attempt = 0; attempt < config2.attemptsPerEndpoint; attempt++) {
40744
- const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config2.responseTimeout;
40745
- const response = yield (0, httpUtil_1.handleRequest)(method, path4, node2.url, requestTimeout, postObject);
40765
+ for (let attempt = 0; attempt < config3.attemptsPerEndpoint; attempt++) {
40766
+ const requestTimeout = timeoutOverride !== null && timeoutOverride !== void 0 ? timeoutOverride : config3.responseTimeout;
40767
+ const response = yield (0, httpUtil_1.handleRequest)(method, path3, node2.url, requestTimeout, postObject);
40746
40768
  error4 = (_b = response === null || response === void 0 ? void 0 : response.error) !== null && _b !== void 0 ? _b : null;
40747
40769
  statusCode = (_c = response === null || response === void 0 ? void 0 : response.statusCode) !== null && _c !== void 0 ? _c : null;
40748
40770
  rspBody = (_d = response === null || response === void 0 ? void 0 : response.rspBody) !== null && _d !== void 0 ? _d : null;
@@ -40760,7 +40782,7 @@ function requireFailoverStrategies() {
40760
40782
  if (isServerError) {
40761
40783
  const duration = getUnreachableDuration(statusCode !== null && statusCode !== void 0 ? statusCode : void 0, response.error);
40762
40784
  nodeManager2.makeNodeUnavailable(node2.url, duration);
40763
- logger2.info(`request failed with server error on ${node2.url} trying next node`);
40785
+ logger3.info(`request failed with server error on ${node2.url} trying next node`);
40764
40786
  break;
40765
40787
  }
40766
40788
  if (isClientError) {
@@ -40768,13 +40790,13 @@ function requireFailoverStrategies() {
40768
40790
  return { error: error4, statusCode, rspBody, transactionTimestamp };
40769
40791
  }
40770
40792
  if (!nodeManager2.useStickyNode) {
40771
- logger2.info(`request failed client error on ${node2.url} trying next node`);
40793
+ logger3.info(`request failed client error on ${node2.url} trying next node`);
40772
40794
  break;
40773
40795
  }
40774
40796
  }
40775
- logger2.info(`${method} request failed on ${node2.url}. Attempt: ${attempt + 1} / ${config2.attemptsPerEndpoint}`);
40776
- if (config2.attemptInterval > 0) {
40777
- yield (0, utils_12.sleep)(config2.attemptInterval);
40797
+ logger3.info(`${method} request failed on ${node2.url}. Attempt: ${attempt + 1} / ${config3.attemptsPerEndpoint}`);
40798
+ if (config3.attemptInterval > 0) {
40799
+ yield (0, utils_12.sleep)(config3.attemptInterval);
40778
40800
  }
40779
40801
  }
40780
40802
  }
@@ -40885,21 +40907,21 @@ function requireRequestWithFailoverStrategy() {
40885
40907
  const enums_12 = enums;
40886
40908
  const failoverStrategies_1 = requireFailoverStrategies();
40887
40909
  function requestWithFailoverStrategy$1(method_1, path_1, config_1, postObject_1) {
40888
- return __awaiter2(this, arguments, void 0, function* (method, path4, config2, postObject, forceSingleEndpoint = false, timeoutOverride) {
40889
- switch (config2.failoverStrategy) {
40910
+ return __awaiter2(this, arguments, void 0, function* (method, path3, config3, postObject, forceSingleEndpoint = false, timeoutOverride) {
40911
+ switch (config3.failoverStrategy) {
40890
40912
  case enums_12.FailoverStrategy.AbortOnError:
40891
- return yield (0, failoverStrategies_1.abortOnError)({ method, path: path4, config: config2, postObject, timeoutOverride });
40913
+ return yield (0, failoverStrategies_1.abortOnError)({ method, path: path3, config: config3, postObject, timeoutOverride });
40892
40914
  case enums_12.FailoverStrategy.TryNextOnError:
40893
- return yield (0, failoverStrategies_1.tryNextOnError)({ method, path: path4, config: config2, postObject, timeoutOverride });
40915
+ return yield (0, failoverStrategies_1.tryNextOnError)({ method, path: path3, config: config3, postObject, timeoutOverride });
40894
40916
  case enums_12.FailoverStrategy.SingleEndpoint:
40895
- return yield (0, failoverStrategies_1.singleEndpoint)({ method, path: path4, config: config2, postObject, timeoutOverride });
40917
+ return yield (0, failoverStrategies_1.singleEndpoint)({ method, path: path3, config: config3, postObject, timeoutOverride });
40896
40918
  case enums_12.FailoverStrategy.QueryMajority:
40897
40919
  if (forceSingleEndpoint) {
40898
- return yield (0, failoverStrategies_1.singleEndpoint)({ method, path: path4, config: config2, postObject, timeoutOverride });
40920
+ return yield (0, failoverStrategies_1.singleEndpoint)({ method, path: path3, config: config3, postObject, timeoutOverride });
40899
40921
  }
40900
- return yield (0, failoverStrategies_1.queryMajority)({ method, path: path4, config: config2, postObject, timeoutOverride });
40922
+ return yield (0, failoverStrategies_1.queryMajority)({ method, path: path3, config: config3, postObject, timeoutOverride });
40901
40923
  default:
40902
- throw new Error(`Unsupported failover strategy: ${config2.failoverStrategy}`);
40924
+ throw new Error(`Unsupported failover strategy: ${config3.failoverStrategy}`);
40903
40925
  }
40904
40926
  });
40905
40927
  }
@@ -41001,7 +41023,7 @@ function requireUtils$1() {
41001
41023
  exports.getBlockchainRidFromIid = getBlockchainRidFromIid;
41002
41024
  exports.convertToPrintable = convertToPrintable;
41003
41025
  const buffer_12 = buffer$3;
41004
- const logger2 = __importStar2(logger$3);
41026
+ const logger3 = __importStar2(logger$3);
41005
41027
  const errors_12 = errors;
41006
41028
  const gtxTool = __importStar2(gtx$1);
41007
41029
  const errors_2 = errors;
@@ -41068,11 +41090,11 @@ function requireUtils$1() {
41068
41090
  return Object.assign(Object.assign(Object.assign({ endpointPool, nodeManager: nodeManager2 }, settings.blockedNodeUrlSubstrings !== void 0 ? { blockedNodeUrlSubstrings: settings.blockedNodeUrlSubstrings } : {}), settings.nodeUrlFilter !== void 0 ? { nodeUrlFilter: settings.nodeUrlFilter } : {}), { blockchainRid: blockchainRidToUse, merkleHashVersion: (_e = settings.merkleHashVersion) !== null && _e !== void 0 ? _e : constants_12.MERKLE_HASH_VERSIONS.UNSET, dappStatusPolling: setStatusPolling(settings.dappStatusPolling), clusterAnchoringStatusPolling: setStatusPolling(settings.clusterAnchoringStatusPolling), systemAnchoringStatusPolling: setStatusPolling(settings.systemAnchoringStatusPolling), retryTransactionPolling: setRetryTransactionPolling(settings.retryTransactionPolling), failoverStrategy: ((_f = settings.failOverConfig) === null || _f === void 0 ? void 0 : _f.strategy) || exports.defaultFailoverConfig.strategy, attemptsPerEndpoint: ((_g = settings.failOverConfig) === null || _g === void 0 ? void 0 : _g.attemptsPerEndpoint) || exports.defaultFailoverConfig.attemptsPerEndpoint, attemptInterval: ((_h = settings.failOverConfig) === null || _h === void 0 ? void 0 : _h.attemptInterval) || exports.defaultFailoverConfig.attemptInterval, unreachableDuration: ((_j = settings.failOverConfig) === null || _j === void 0 ? void 0 : _j.unreachableDuration) || exports.defaultFailoverConfig.unreachableDuration, directoryChainRid: settings.directoryChainRid || directoryChainRid, connectTimeout: settings.connectTimeout, responseTimeout: settings.responseTimeout });
41069
41091
  });
41070
41092
  }
41071
- function getMerkleHashVersionFromDapp(config2) {
41093
+ function getMerkleHashVersionFromDapp(config3) {
41072
41094
  return __awaiter2(this, void 0, void 0, function* () {
41073
41095
  var _a2;
41074
41096
  try {
41075
- const response = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/config/${config2.blockchainRid}/features`, config2, void 0, false, (_a2 = config2.connectTimeout) !== null && _a2 !== void 0 ? _a2 : config2.responseTimeout);
41097
+ const response = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/config/${config3.blockchainRid}/features`, config3, void 0, false, (_a2 = config3.connectTimeout) !== null && _a2 !== void 0 ? _a2 : config3.responseTimeout);
41076
41098
  const validatedResponse = (0, merkleHash_1.validateMerkleHash)(response.rspBody);
41077
41099
  return validatedResponse.merkle_hash_version;
41078
41100
  } catch (error4) {
@@ -41084,7 +41106,7 @@ function requireUtils$1() {
41084
41106
  function validTxRid(txRID) {
41085
41107
  if (txRID.length != 32) {
41086
41108
  const error4 = new errors_12.InvalidTxRidException(txRID);
41087
- logger2.error(error4.toString());
41109
+ logger3.error(error4.toString());
41088
41110
  return false;
41089
41111
  }
41090
41112
  return true;
@@ -41487,7 +41509,7 @@ function requireUtils$1() {
41487
41509
  function handleGetResponse(error4, statusCode, responseObject, callback) {
41488
41510
  try {
41489
41511
  const responseObjectPrintable = convertToPrintable(responseObject);
41490
- logger2.debug(`error: ${error4}, status code: ${statusCode}, response body: ${responseObjectPrintable}`);
41512
+ logger3.debug(`error: ${error4}, status code: ${statusCode}, response body: ${responseObjectPrintable}`);
41491
41513
  if (error4) {
41492
41514
  return callback(error4, null);
41493
41515
  }
@@ -41497,16 +41519,16 @@ function requireUtils$1() {
41497
41519
  return callback(null, responseObject);
41498
41520
  } catch (error5) {
41499
41521
  callback(error5, null);
41500
- logger2.error(`client.handleGetResponse(): Failed to call the callback function. ${error5}`);
41522
+ logger3.error(`client.handleGetResponse(): Failed to call the callback function. ${error5}`);
41501
41523
  }
41502
41524
  }
41503
41525
  function handlePostResponse(error4, statusCode, responseObject, callback) {
41504
41526
  var _a2;
41505
41527
  const responseObjectPrintable = convertToPrintable(responseObject);
41506
- logger2.debug(`error: ${error4}, status code: ${statusCode}, response body: ${responseObjectPrintable}`);
41528
+ logger3.debug(`error: ${error4}, status code: ${statusCode}, response body: ${responseObjectPrintable}`);
41507
41529
  try {
41508
41530
  if (error4) {
41509
- logger2.error(`In client post(). ${error4}`);
41531
+ logger3.error(`In client post(). ${error4}`);
41510
41532
  callback(error4, null);
41511
41533
  } else if (!statusCode || !(0, http_utils_1.isSuccessfulStatusCode)(statusCode)) {
41512
41534
  let errorMessage2 = `Unexpected status code from server. Code: ${statusCode}.`;
@@ -41514,21 +41536,21 @@ function requireUtils$1() {
41514
41536
  if (responseObjectPrintable) {
41515
41537
  errorMessage2 += ` Message: ${responseObjectPrintable}.`;
41516
41538
  }
41517
- logger2.error(errorMessage2);
41539
+ logger3.error(errorMessage2);
41518
41540
  callback(new errors_12.UnexpectedStatusError(statusCode !== null && statusCode !== void 0 ? statusCode : 400, errorMessageInResponseBody || responseObjectPrintable), responseObject);
41519
41541
  } else {
41520
- logger2.info(`Calling responseCallback with responseObject: ${responseObjectPrintable}`);
41542
+ logger3.info(`Calling responseCallback with responseObject: ${responseObjectPrintable}`);
41521
41543
  callback(null, responseObject);
41522
41544
  }
41523
41545
  } catch (error5) {
41524
- logger2.error(`client.handlePostResponse(): Failed to call callback function ${error5}`);
41546
+ logger3.error(`client.handlePostResponse(): Failed to call callback function ${error5}`);
41525
41547
  }
41526
41548
  }
41527
41549
  function getBlockchainRidFromIid(_a2) {
41528
41550
  return __awaiter2(this, arguments, void 0, function* ({ endpointPool, chainId, failOverConfig = {}, nodeManager: nodeManager2, connectTimeout, responseTimeout }) {
41529
41551
  var _b;
41530
41552
  const mergedFailOverConfig = Object.assign(Object.assign({}, exports.defaultFailoverConfig), failOverConfig);
41531
- const config2 = {
41553
+ const config3 = {
41532
41554
  endpointPool,
41533
41555
  nodeManager: nodeManager2,
41534
41556
  dappStatusPolling: setStatusPolling(),
@@ -41543,7 +41565,7 @@ function requireUtils$1() {
41543
41565
  connectTimeout,
41544
41566
  responseTimeout
41545
41567
  };
41546
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/brid/iid_${chainId}`, config2, void 0, false, (_b = config2.connectTimeout) !== null && _b !== void 0 ? _b : config2.responseTimeout);
41568
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/brid/iid_${chainId}`, config3, void 0, false, (_b = config3.connectTimeout) !== null && _b !== void 0 ? _b : config3.responseTimeout);
41547
41569
  const blockchainRid = (0, requests_1.isString)(rspBody);
41548
41570
  if (!blockchainRid) {
41549
41571
  throw error4;
@@ -42096,7 +42118,7 @@ var networkSettings = {};
42096
42118
  const restNetworkSettingsValidationContext = RestNetworkSettingsSchema.safeParse(networkSettings2);
42097
42119
  if ("error" in restNetworkSettingsValidationContext) {
42098
42120
  const { error: { issues } = {} } = restNetworkSettingsValidationContext;
42099
- const errorMessage2 = issues === null || issues === void 0 ? void 0 : issues.map(({ message, path: path4 }) => `${path4[0]}: ${message}`).join(", ");
42121
+ const errorMessage2 = issues === null || issues === void 0 ? void 0 : issues.map(({ message, path: path3 }) => `${path3[0]}: ${message}`).join(", ");
42100
42122
  if (throwOnError) {
42101
42123
  throw new Error(errorMessage2);
42102
42124
  }
@@ -42259,7 +42281,7 @@ function requireBlockchainClient() {
42259
42281
  const crypto_12 = requireCryptoBrowserify();
42260
42282
  const cloneDeep_1$1 = __importDefault2(cloneDeep_1);
42261
42283
  const IccfProofTxMaterialBuilder_1 = requireIccfProofTxMaterialBuilder();
42262
- const logger2 = __importStar2(logger$3);
42284
+ const logger3 = __importStar2(logger$3);
42263
42285
  const formatter_12 = formatter;
42264
42286
  const serialization_12 = serialization$2;
42265
42287
  const gtxTool = __importStar2(gtx$1);
@@ -42279,10 +42301,10 @@ function requireBlockchainClient() {
42279
42301
  function createClient(settings) {
42280
42302
  return __awaiter2(this, void 0, void 0, function* () {
42281
42303
  (0, networkSettings_1.isNetworkSettingValid)(settings, { throwOnError: true });
42282
- const config2 = yield (0, utils_12.getClientConfigFromSettings)(settings);
42283
- config2.merkleHashVersion = yield getMerkleHashVersion(settings);
42304
+ const config3 = yield (0, utils_12.getClientConfigFromSettings)(settings);
42305
+ config3.merkleHashVersion = yield getMerkleHashVersion(settings);
42284
42306
  return {
42285
- config: config2,
42307
+ config: config3,
42286
42308
  query(nameOrQueryObject, args, callback) {
42287
42309
  return __awaiter2(this, void 0, void 0, function* () {
42288
42310
  let _name, _args;
@@ -42293,7 +42315,7 @@ function requireBlockchainClient() {
42293
42315
  _name = nameOrQueryObject === null || nameOrQueryObject === void 0 ? void 0 : nameOrQueryObject.name;
42294
42316
  _args = nameOrQueryObject === null || nameOrQueryObject === void 0 ? void 0 : nameOrQueryObject.args;
42295
42317
  }
42296
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.POST, `query_gtv/${config2.blockchainRid}`, config2, (0, serialization_12.encodeValue)((0, formatter_12.toQueryObjectGTV)(_name, _args)));
42318
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.POST, `query_gtv/${config3.blockchainRid}`, config3, (0, serialization_12.encodeValue)((0, formatter_12.toQueryObjectGTV)(_name, _args)));
42297
42319
  return new Promise((resolve2, reject) => {
42298
42320
  (0, utils_12.handlePostResponse)(error4, statusCode, (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
42299
42321
  });
@@ -42301,10 +42323,10 @@ function requireBlockchainClient() {
42301
42323
  },
42302
42324
  signTransaction(transaction, signMethod2, callback) {
42303
42325
  return __awaiter2(this, void 0, void 0, function* () {
42304
- logger2.debug(`Signing transaction with ${!(0, utils_12.isKeyPair)(signMethod2) ? "signature provider containing " : ""}pubKey: ${(0, formatter_12.toString)(signMethod2.pubKey)}`);
42305
- const gtx2 = (0, utils_12.getGTXFromBufferOrTransactionOrOperation)(transaction, config2.blockchainRid);
42326
+ logger3.debug(`Signing transaction with ${!(0, utils_12.isKeyPair)(signMethod2) ? "signature provider containing " : ""}pubKey: ${(0, formatter_12.toString)(signMethod2.pubKey)}`);
42327
+ const gtx2 = (0, utils_12.getGTXFromBufferOrTransactionOrOperation)(transaction, config3.blockchainRid);
42306
42328
  try {
42307
- const signedTx = yield (0, utils_12.isKeyPair)(signMethod2) ? gtxTool.sign(gtx2, signMethod2.privKey, config2.merkleHashVersion, signMethod2.pubKey) : gtxTool.sign(gtx2, signMethod2, config2.merkleHashVersion);
42329
+ const signedTx = yield (0, utils_12.isKeyPair)(signMethod2) ? gtxTool.sign(gtx2, signMethod2.privKey, config3.merkleHashVersion, signMethod2.pubKey) : gtxTool.sign(gtx2, signMethod2, config3.merkleHashVersion);
42308
42330
  const gtxBytes = (0, utils_12.getSerializedGTX)(signedTx);
42309
42331
  if (typeof callback === "function") {
42310
42332
  callback(null, gtxBytes);
@@ -42325,8 +42347,8 @@ function requireBlockchainClient() {
42325
42347
  }
42326
42348
  const promiEvent = new promiEvents_12.Web3PromiEvent((resolve2, reject) => __awaiter2(this, void 0, void 0, function* () {
42327
42349
  let error4 = null;
42328
- for (let i = 0; i < config2.retryTransactionPolling.count; i++) {
42329
- logger2.info(`sendTransactionWithRetries attempt ${i + 1} of ${config2.retryTransactionPolling.count}`);
42350
+ for (let i = 0; i < config3.retryTransactionPolling.count; i++) {
42351
+ logger3.info(`sendTransactionWithRetries attempt ${i + 1} of ${config3.retryTransactionPolling.count}`);
42330
42352
  const tmpPromiEvent = sendOnce().on(enums_12.TransactionEvent.ClusterAnchoringConfirmation, (receipt) => {
42331
42353
  promiEvent.emit(enums_12.TransactionEvent.ClusterAnchoringConfirmation, receipt);
42332
42354
  }).on(enums_12.TransactionEvent.SystemAnchoringConfirmation, (receipt) => {
@@ -42338,7 +42360,7 @@ function requireBlockchainClient() {
42338
42360
  }).on(enums_12.TransactionEvent.DappConfirmed, (receipt) => {
42339
42361
  promiEvent.emit(enums_12.TransactionEvent.DappConfirmed, receipt);
42340
42362
  }).catch((tmpError) => {
42341
- logger2.warning(`sendTransactionWithRetries error on attempt ${i + 1} of ${config2.retryTransactionPolling.count}: ${tmpError}`);
42363
+ logger3.warning(`sendTransactionWithRetries error on attempt ${i + 1} of ${config3.retryTransactionPolling.count}: ${tmpError}`);
42342
42364
  promiEvent.emit(enums_12.TransactionEvent.Rejected, tmpError);
42343
42365
  error4 = tmpError;
42344
42366
  });
@@ -42347,7 +42369,7 @@ function requireBlockchainClient() {
42347
42369
  resolve2(tmpReceipt);
42348
42370
  return;
42349
42371
  }
42350
- yield (0, utils_12.sleep)(config2.retryTransactionPolling.interval);
42372
+ yield (0, utils_12.sleep)(config3.retryTransactionPolling.interval);
42351
42373
  }
42352
42374
  reject(error4);
42353
42375
  }));
@@ -42357,13 +42379,13 @@ function requireBlockchainClient() {
42357
42379
  const promiEvent = new promiEvents_12.Web3PromiEvent((resolve2, reject) => __awaiter2(this, void 0, void 0, function* () {
42358
42380
  var _a2, _b;
42359
42381
  try {
42360
- const gtx2 = (0, utils_12.getGTXFromBufferOrTransactionOrOperation)(transaction, config2.blockchainRid);
42382
+ const gtx2 = (0, utils_12.getGTXFromBufferOrTransactionOrOperation)(transaction, config3.blockchainRid);
42361
42383
  if (gtx2.signers.length !== ((_a2 = gtx2.signatures) === null || _a2 === void 0 ? void 0 : _a2.length)) {
42362
42384
  reject(new errors_12.NumberOfSignersAndSignaturesException());
42363
42385
  }
42364
42386
  const gtxBytes = (0, utils_12.getSerializedGTX)(gtx2);
42365
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.POST, `tx/${config2.blockchainRid}`, config2, gtxBytes);
42366
- const transactionRid = gtxTool.getDigestToSign(gtx2, config2.merkleHashVersion);
42387
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.POST, `tx/${config3.blockchainRid}`, config3, gtxBytes);
42388
+ const transactionRid = gtxTool.getDigestToSign(gtx2, config3.merkleHashVersion);
42367
42389
  try {
42368
42390
  yield (0, utils_12.handlePostResponsePromisified)(error4, statusCode, (0, requests_1.isRawGtv)(rspBody));
42369
42391
  if (typeof callback === "function") {
@@ -42371,7 +42393,7 @@ function requireBlockchainClient() {
42371
42393
  status: enums_12.ResponseStatus.Waiting,
42372
42394
  statusCode,
42373
42395
  transactionRid,
42374
- node: (_b = config2.nodeManager.lastUsedNode) === null || _b === void 0 ? void 0 : _b.url
42396
+ node: (_b = config3.nodeManager.lastUsedNode) === null || _b === void 0 ? void 0 : _b.url
42375
42397
  });
42376
42398
  }
42377
42399
  } catch (_error) {
@@ -42434,7 +42456,7 @@ function requireBlockchainClient() {
42434
42456
  callback === null || callback === void 0 ? void 0 : callback(error5, null);
42435
42457
  throw error5;
42436
42458
  }
42437
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config2.blockchainRid}/${(0, formatter_12.ensureString)(transactionRid)}`, config2);
42459
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config3.blockchainRid}/${(0, formatter_12.ensureString)(transactionRid)}`, config3);
42438
42460
  const transaction = (0, requests_1.isTransaction)(rspBody);
42439
42461
  return new Promise((resolve2, reject) => {
42440
42462
  (0, utils_12.handleGetResponse)(error4, statusCode, statusCode === 200 && transaction ? (0, formatter_12.toBuffer)(transaction.tx) : (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
@@ -42449,7 +42471,7 @@ function requireBlockchainClient() {
42449
42471
  callback === null || callback === void 0 ? void 0 : callback(error5, null);
42450
42472
  throw error5;
42451
42473
  }
42452
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config2.blockchainRid}/${transactionRid.toString("hex")}/status`, config2);
42474
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config3.blockchainRid}/${transactionRid.toString("hex")}/status`, config3);
42453
42475
  return new Promise((resolve2, reject) => {
42454
42476
  (0, utils_12.handleGetResponse)(error4, statusCode, (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, (result) => resolve2((0, transactionStatusReponse_1.validateTransactionStatusReponse)({
42455
42477
  statusCode,
@@ -42472,7 +42494,7 @@ function requireBlockchainClient() {
42472
42494
  const beforeTimeQueryParam = beforeTime ? `&before-time=${beforeTime.getTime()}` : "";
42473
42495
  const afterTimeQueryParam = afterTime ? `&after-time=${afterTime.getTime()}` : "";
42474
42496
  const signerQueryParam = signerPubKey ? `&signer=${signerPubKey}` : "";
42475
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config2.blockchainRid}?limit=${limit}${beforeTimeQueryParam}${afterTimeQueryParam}${signerQueryParam}`, config2);
42497
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config3.blockchainRid}?limit=${limit}${beforeTimeQueryParam}${afterTimeQueryParam}${signerQueryParam}`, config3);
42476
42498
  const transactionsInfoResponseArray = (0, requests_1.isTransactionInfoResponseArray)(rspBody);
42477
42499
  const body = statusCode === 200 && transactionsInfoResponseArray ? transactionsInfoResponseArray.map(utils_12.formatTransactionInfoResponse) : rspBody;
42478
42500
  return new Promise((resolve2, reject) => {
@@ -42488,7 +42510,7 @@ function requireBlockchainClient() {
42488
42510
  callback === null || callback === void 0 ? void 0 : callback(error5, null);
42489
42511
  throw error5;
42490
42512
  }
42491
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config2.blockchainRid}/${(0, formatter_12.ensureString)(transactionRid)}`, config2);
42513
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config3.blockchainRid}/${(0, formatter_12.ensureString)(transactionRid)}`, config3);
42492
42514
  const transactionInfoResponse = (0, requests_1.isTransactionInfoResponse)(rspBody);
42493
42515
  const body = statusCode === 200 && transactionInfoResponse ? (0, utils_12.formatTransactionInfoResponse)(transactionInfoResponse) : rspBody;
42494
42516
  return new Promise((resolve2, reject) => {
@@ -42500,7 +42522,7 @@ function requireBlockchainClient() {
42500
42522
  return __awaiter2(this, void 0, void 0, function* () {
42501
42523
  const client = this;
42502
42524
  const result = { status: enums_12.AnchoringStatus.NotAnchored };
42503
- const clusterAnchoredTx = yield (0, utils_2.awaitGetAnchoringTransactionForBlockRid)(anchoringClient, (0, formatter_12.ensureBuffer)(client.config.blockchainRid), (0, formatter_12.ensureBuffer)(blockRid), config2.clusterAnchoringStatusPolling);
42525
+ const clusterAnchoredTx = yield (0, utils_2.awaitGetAnchoringTransactionForBlockRid)(anchoringClient, (0, formatter_12.ensureBuffer)(client.config.blockchainRid), (0, formatter_12.ensureBuffer)(blockRid), config3.clusterAnchoringStatusPolling);
42504
42526
  if (!clusterAnchoredTx) {
42505
42527
  return result;
42506
42528
  }
@@ -42510,7 +42532,7 @@ function requireBlockchainClient() {
42510
42532
  }
42511
42533
  result.status = enums_12.AnchoringStatus.ClusterAnchored;
42512
42534
  result.clusterAnchoredTx = anchoringTransactionValidation.data;
42513
- const systemAnchoredTransaction = yield (0, utils_12.getSystemAnchoringTransaction)(config2.endpointPool, anchoringTransactionValidation.data.txRid, anchoringClient, systemAnchoringChainRid, config2.systemAnchoringStatusPolling, config2.merkleHashVersion, config2.blockedNodeUrlSubstrings, config2.nodeUrlFilter);
42535
+ const systemAnchoredTransaction = yield (0, utils_12.getSystemAnchoringTransaction)(config3.endpointPool, anchoringTransactionValidation.data.txRid, anchoringClient, systemAnchoringChainRid, config3.systemAnchoringStatusPolling, config3.merkleHashVersion, config3.blockedNodeUrlSubstrings, config3.nodeUrlFilter);
42514
42536
  if (!systemAnchoredTransaction) {
42515
42537
  return result;
42516
42538
  }
@@ -42574,7 +42596,7 @@ function requireBlockchainClient() {
42574
42596
  },
42575
42597
  getTransactionCount(callback) {
42576
42598
  return __awaiter2(this, void 0, void 0, function* () {
42577
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config2.blockchainRid}/count`, config2, void 0, true);
42599
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `transactions/${config3.blockchainRid}/count`, config3, void 0, true);
42578
42600
  const transactionsCount = (0, requests_1.isTransactionsCount)(rspBody);
42579
42601
  return new Promise((resolve2, reject) => {
42580
42602
  (0, utils_12.handleGetResponse)(error4, statusCode, statusCode === 200 ? transactionsCount === null || transactionsCount === void 0 ? void 0 : transactionsCount.transactionsCount : (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
@@ -42585,7 +42607,7 @@ function requireBlockchainClient() {
42585
42607
  return __awaiter2(this, arguments, void 0, function* (blockIdentifier2, txs = false, callback) {
42586
42608
  (0, blockIdentifier_1.isBlockIdentifierValid)(blockIdentifier2, { throwOnError: true });
42587
42609
  const queryString = typeof blockIdentifier2 === "string" ? blockIdentifier2 : `height/${blockIdentifier2}`;
42588
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config2.blockchainRid}/${queryString}?txs=${txs}`, config2);
42610
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config3.blockchainRid}/${queryString}?txs=${txs}`, config3);
42589
42611
  const blockInfoResponse = (0, requests_1.isBlockInfoResponse)(rspBody);
42590
42612
  return new Promise((resolve2, reject) => {
42591
42613
  (0, utils_12.handleGetResponse)(error4, statusCode, statusCode === 200 && blockInfoResponse !== null && blockInfoResponse ? (0, utils_12.formatBlockInfoResponse)(blockInfoResponse) : (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
@@ -42595,7 +42617,7 @@ function requireBlockchainClient() {
42595
42617
  getLatestBlock() {
42596
42618
  return __awaiter2(this, arguments, void 0, function* (txs = false, callback) {
42597
42619
  const shouldIncludeFullTransaction = txs ? `&txs=${txs}` : "";
42598
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config2.blockchainRid}?limit=1${shouldIncludeFullTransaction}`, config2, void 0, true);
42620
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config3.blockchainRid}?limit=1${shouldIncludeFullTransaction}`, config3, void 0, true);
42599
42621
  const indexOfLatestBlock = 0;
42600
42622
  const blockInfoResponseArray = (0, requests_1.isBlockInfoResponseArray)(rspBody);
42601
42623
  return new Promise((resolve2, reject) => {
@@ -42620,7 +42642,7 @@ function requireBlockchainClient() {
42620
42642
  searchParams.append(key3, value.toString());
42621
42643
  }
42622
42644
  }
42623
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config2.blockchainRid}?${searchParams}`, config2);
42645
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `blocks/${config3.blockchainRid}?${searchParams}`, config3);
42624
42646
  const blockInfoResponseArray = (0, requests_1.isBlockInfoResponseArray)(rspBody);
42625
42647
  return new Promise((resolve2, reject) => {
42626
42648
  (0, utils_12.handleGetResponse)(error4, statusCode, statusCode === 200 && blockInfoResponseArray ? blockInfoResponseArray.map(utils_12.formatBlockInfoResponse) : (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
@@ -42628,7 +42650,7 @@ function requireBlockchainClient() {
42628
42650
  });
42629
42651
  },
42630
42652
  getClientNodeUrlPool() {
42631
- return config2.endpointPool.map((endpoint) => endpoint.url);
42653
+ return config3.endpointPool.map((endpoint) => endpoint.url);
42632
42654
  },
42633
42655
  /**
42634
42656
  * Retrieves a confirmation proof for a transaction with the specified sha256
@@ -42663,7 +42685,7 @@ function requireBlockchainClient() {
42663
42685
  callback === null || callback === void 0 ? void 0 : callback(error5, null);
42664
42686
  throw error5;
42665
42687
  }
42666
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config2.blockchainRid}/${(0, formatter_12.ensureString)(txRid2)}/confirmationProof`, config2);
42688
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `tx/${config3.blockchainRid}/${(0, formatter_12.ensureString)(txRid2)}/confirmationProof`, config3);
42667
42689
  const confirmationProof = {
42668
42690
  merkleProofTree: "",
42669
42691
  txIndex: 0
@@ -42727,13 +42749,13 @@ function requireBlockchainClient() {
42727
42749
  callback === null || callback === void 0 ? void 0 : callback(error4, null);
42728
42750
  throw error4;
42729
42751
  }
42730
- const systemAnchoringTransactionTransaction = yield (0, utils_12.getSystemAnchoringTransaction)(config2.endpointPool, anchoredTxRid, anchoringClient, systemAnchoringChainRid, config2.systemAnchoringStatusPolling, config2.merkleHashVersion, config2.blockedNodeUrlSubstrings, config2.nodeUrlFilter);
42752
+ const systemAnchoringTransactionTransaction = yield (0, utils_12.getSystemAnchoringTransaction)(config3.endpointPool, anchoredTxRid, anchoringClient, systemAnchoringChainRid, config3.systemAnchoringStatusPolling, config3.merkleHashVersion, config3.blockedNodeUrlSubstrings, config3.nodeUrlFilter);
42731
42753
  return systemAnchoringTransactionTransaction;
42732
42754
  });
42733
42755
  },
42734
42756
  getWaitingTransactions(blockchainRid, callback) {
42735
42757
  return __awaiter2(this, void 0, void 0, function* () {
42736
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/waiting`, config2);
42758
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/waiting`, config3);
42737
42759
  return new Promise((resolve2, reject) => {
42738
42760
  (0, utils_12.handleGetResponse)(error4, statusCode, (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
42739
42761
  });
@@ -42741,7 +42763,7 @@ function requireBlockchainClient() {
42741
42763
  },
42742
42764
  getWaitingTransaction(blockchainRid, txRid2, callback) {
42743
42765
  return __awaiter2(this, void 0, void 0, function* () {
42744
- const { error: error4, statusCode, rspBody, transactionTimestamp } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/waiting/${(0, formatter_12.ensureString)(txRid2)}`, config2);
42766
+ const { error: error4, statusCode, rspBody, transactionTimestamp } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/waiting/${(0, formatter_12.ensureString)(txRid2)}`, config3);
42745
42767
  const transaction = (0, requests_1.isTransaction)(rspBody);
42746
42768
  const result = transaction ? (0, formatter_12.toBuffer)(transaction.tx) : (0, requests_1.isRawGtv)(rspBody);
42747
42769
  return new Promise((resolve2, reject) => {
@@ -42754,7 +42776,7 @@ function requireBlockchainClient() {
42754
42776
  },
42755
42777
  getRejectedTransactions(blockchainRid, callback) {
42756
42778
  return __awaiter2(this, void 0, void 0, function* () {
42757
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/rejected`, config2);
42779
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/tx/${(0, formatter_12.ensureString)(blockchainRid)}/rejected`, config3);
42758
42780
  const rejectedTransactionsArray = (0, requests_1.isRejectedTransactionResponseArray)(rspBody);
42759
42781
  const validResponseBody = statusCode === 200 && rejectedTransactionsArray ? rejectedTransactionsArray.map((rejectedTransaction) => (0, utils_12.formatRejectedTransactionFromResponse)(rejectedTransaction)) : rspBody;
42760
42782
  return new Promise((resolve2, reject) => {
@@ -42768,7 +42790,7 @@ function requireBlockchainClient() {
42768
42790
  */
42769
42791
  getAppStructure(callback) {
42770
42792
  return __awaiter2(this, void 0, void 0, function* () {
42771
- const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/query/${config2.blockchainRid}?type=rell.get_app_structure`, config2);
42793
+ const { error: error4, statusCode, rspBody } = yield (0, requestWithFailoverStrategy_1.requestWithFailoverStrategy)(enums_12.Method.GET, `/query/${config3.blockchainRid}?type=rell.get_app_structure`, config3);
42772
42794
  return new Promise((resolve2, reject) => {
42773
42795
  (0, utils_12.handleGetResponse)(error4, statusCode, (0, requests_1.isRawGtv)(rspBody), (0, utils_12.callbackPromiseBuilder)(reject, resolve2, callback));
42774
42796
  });
@@ -42781,7 +42803,7 @@ function requireBlockchainClient() {
42781
42803
  if (settings2.merkleHashVersion !== void 0) {
42782
42804
  merkleHashVersion = settings2.merkleHashVersion;
42783
42805
  } else {
42784
- merkleHashVersion = yield (0, utils_12.getMerkleHashVersionFromDapp)(config2);
42806
+ merkleHashVersion = yield (0, utils_12.getMerkleHashVersionFromDapp)(config3);
42785
42807
  }
42786
42808
  return merkleHashVersion;
42787
42809
  });
@@ -43073,11 +43095,11 @@ function requireDecodeTransactionToGtx() {
43073
43095
  Object.defineProperty(decodeTransactionToGtx, "__esModule", { value: true });
43074
43096
  decodeTransactionToGtx.decodeTransactionToGtx = decodeTransactionToGtx$1;
43075
43097
  const gtxTool = __importStar2(gtx$1);
43076
- const logger2 = __importStar2(logger$3);
43098
+ const logger3 = __importStar2(logger$3);
43077
43099
  const dump_1 = requireDump();
43078
43100
  function decodeTransactionToGtx$1(encodedTransaction) {
43079
43101
  const gtx2 = gtxTool.deserialize(encodedTransaction);
43080
- logger2.debug(`Output from deserializing a raw transaction: ${(0, dump_1.dumpGtv)(gtx2)}`);
43102
+ logger3.debug(`Output from deserializing a raw transaction: ${(0, dump_1.dumpGtv)(gtx2)}`);
43081
43103
  return gtx2;
43082
43104
  }
43083
43105
  return decodeTransactionToGtx;
@@ -43294,10 +43316,8 @@ var index = /* @__PURE__ */ getDefaultExportFromCjs(builtExports);
43294
43316
 
43295
43317
  // src-ts/browser/native.ts
43296
43318
  var { Buffer: Buffer3, gtx: pcgtx } = index;
43297
- var ATBASH_ENDPOINT = "https://chromia-verified-ai-dev-two.vercel.app";
43298
- var ATBASH_BLOCKCHAIN_RID = "02668C5218871F69A93CC0F7032DCFFE06EF0D35EF2F0B07A92A3D83A3F23A7D";
43299
- var ATBASH_PRIVATE_BLOCKCHAIN_RID = "2603569AE8DC3F254323F719C8D4347BBA964E874E781291F8474236BE8B6493";
43300
- var DEFAULT_CHROMIA_NODE_URLS_ARR = define_ATBASH_CHROMIA_NODE_URLS_default;
43319
+ var ATBASH_ENDPOINT = "https://atbash.ai";
43320
+ var ATBASH_PRIVATE_BLOCKCHAIN_RID = "39FFD3557D0296CB2C57FDC6A3B8C024E95639CF4964DA08141AC20C6344D408";
43301
43321
  var DEFAULT_PRIVATE_NODE_URLS_ARR = define_ATBASH_PRIVATE_NODE_URLS_default;
43302
43322
  var MERKLE_HASH_VERSION = 2;
43303
43323
  function stripHex(s2) {
@@ -43399,6 +43419,17 @@ function verifySignature(body, signatureHex, pubkeyHex) {
43399
43419
  const sigBytes = hexToBytes2(sigClean);
43400
43420
  return secp256k1.verify(sigBytes, digest9, pkBytes, { prehash: false });
43401
43421
  }
43422
+ function pinnedJudgeVerifyKeys(host) {
43423
+ const h = host.trim().toLowerCase();
43424
+ if (h === "atbash.ai" || h === "www.atbash.ai") return [...define_ATBASH_PROD_JUDGE_PINS_default];
43425
+ let devHost = "";
43426
+ try {
43427
+ devHost = "https://chromia-verified-ai-dev-two.vercel.app" ? new URL("https://chromia-verified-ai-dev-two.vercel.app").hostname.toLowerCase() : "";
43428
+ } catch {
43429
+ devHost = "";
43430
+ }
43431
+ return devHost !== "" && h === devHost ? [...define_ATBASH_DEV_JUDGE_PINS_default] : [];
43432
+ }
43402
43433
  var STUB_MSG = "not available in @atbash/sdk browser bundle \u2014 call from Node or handle server-side";
43403
43434
  function redactSecrets(input) {
43404
43435
  return { redacted: input, found: [] };
@@ -43440,6 +43471,7 @@ var native = {
43440
43471
  signLogToolCall,
43441
43472
  signJudgeAction,
43442
43473
  verifySignature,
43474
+ pinnedJudgeVerifyKeys,
43443
43475
  normalizeForMatching,
43444
43476
  containsEvasionCharacters,
43445
43477
  redactSecrets,
@@ -43449,12 +43481,21 @@ var native = {
43449
43481
  deriveMemoryKey,
43450
43482
  encryptMemoryContent,
43451
43483
  decryptMemoryContent,
43452
- DEFAULT_BLOCKCHAIN_RID: ATBASH_BLOCKCHAIN_RID,
43453
43484
  DEFAULT_PRIVATE_BLOCKCHAIN_RID: ATBASH_PRIVATE_BLOCKCHAIN_RID,
43454
43485
  DEFAULT_ENDPOINT: ATBASH_ENDPOINT,
43455
- defaultChromiaNodeUrls: () => [...DEFAULT_CHROMIA_NODE_URLS_ARR],
43456
43486
  defaultPrivateNodeUrls: () => [...DEFAULT_PRIVATE_NODE_URLS_ARR],
43457
43487
  // Server-only surfaces — throw at runtime, keep types satisfied.
43488
+ // The memory signers are here and not with the other signing shims because
43489
+ // their args are encrypted by `encryptMemoryContent`, which this build does
43490
+ // not have: a browser could sign the transaction but never produce one worth
43491
+ // sending.
43492
+ signAddAgentMemory: stub("signAddAgentMemory"),
43493
+ signRollbackAgentMemory: stub("signRollbackAgentMemory"),
43494
+ extractMemoryEdits: stub("extractMemoryEdits"),
43495
+ applyMemoryEdits: stub("applyMemoryEdits"),
43496
+ memorySlotForPath: stub("memorySlotForPath"),
43497
+ isSafeMemorySlot: stub("isSafeMemorySlot"),
43498
+ defaultAgentHomeDirs: stub("defaultAgentHomeDirs"),
43458
43499
  classifyMemoryWrite: stub("classifyMemoryWrite"),
43459
43500
  classifyMemoryRead: stub("classifyMemoryRead"),
43460
43501
  defaultMemoryWriteToolNames: stub("defaultMemoryWriteToolNames"),
@@ -43511,12 +43552,14 @@ var native = {
43511
43552
  };
43512
43553
 
43513
43554
  // src-ts/client.ts
43514
- init_define_ATBASH_CHROMIA_NODE_URLS();
43555
+ init_define_ATBASH_DEV_JUDGE_PINS();
43515
43556
  init_define_ATBASH_PRIVATE_NODE_URLS();
43557
+ init_define_ATBASH_PROD_JUDGE_PINS();
43516
43558
 
43517
43559
  // src-ts/random.ts
43518
- init_define_ATBASH_CHROMIA_NODE_URLS();
43560
+ init_define_ATBASH_DEV_JUDGE_PINS();
43519
43561
  init_define_ATBASH_PRIVATE_NODE_URLS();
43562
+ init_define_ATBASH_PROD_JUDGE_PINS();
43520
43563
  function randomBytes4(size) {
43521
43564
  const buf = new Uint8Array(size);
43522
43565
  globalThis.crypto.getRandomValues(buf);
@@ -43531,49 +43574,75 @@ function randomHex(size) {
43531
43574
  return hex;
43532
43575
  }
43533
43576
 
43534
- // src-ts/chain-config.ts
43535
- init_define_ATBASH_CHROMIA_NODE_URLS();
43536
- init_define_ATBASH_PRIVATE_NODE_URLS();
43537
-
43538
- // src-ts/constants.ts
43539
- init_define_ATBASH_CHROMIA_NODE_URLS();
43577
+ // src-ts/auth-bearer.ts
43578
+ init_define_ATBASH_DEV_JUDGE_PINS();
43540
43579
  init_define_ATBASH_PRIVATE_NODE_URLS();
43541
- var DEFAULT_ENDPOINT = native.DEFAULT_ENDPOINT;
43542
- var DEFAULT_CHROMIA_NODE_URLS = Object.freeze(
43543
- native.defaultChromiaNodeUrls()
43544
- );
43545
- var DEFAULT_BLOCKCHAIN_RID = native.DEFAULT_BLOCKCHAIN_RID;
43580
+ init_define_ATBASH_PROD_JUDGE_PINS();
43581
+ var BEARER_TTL_MS = 4 * 60 * 1e3;
43582
+ var bearers = /* @__PURE__ */ new Map();
43583
+ function agentAuthBearer(auth, blockchainRid) {
43584
+ const key3 = `${auth.pubkey}:${blockchainRid}`;
43585
+ const now = Date.now();
43586
+ const cached = bearers.get(key3);
43587
+ if (cached && now - cached.issuedAt < BEARER_TTL_MS) return cached.hex;
43588
+ const hex = native.signLogToolCall(
43589
+ `auth-${now.toString(36)}-${randomHex(4)}`,
43590
+ `auth:${now}`,
43591
+ "",
43592
+ "auth-bearer",
43593
+ "",
43594
+ auth.privkey,
43595
+ blockchainRid
43596
+ );
43597
+ bearers.set(key3, { hex, issuedAt: now });
43598
+ return hex;
43599
+ }
43600
+ function agentAuthHeaders(auth, blockchainRid) {
43601
+ return { Authorization: `Bearer ${agentAuthBearer(auth, blockchainRid)}` };
43602
+ }
43546
43603
 
43547
43604
  // src-ts/chain-config.ts
43605
+ init_define_ATBASH_DEV_JUDGE_PINS();
43606
+ init_define_ATBASH_PRIVATE_NODE_URLS();
43607
+ init_define_ATBASH_PROD_JUDGE_PINS();
43548
43608
  var DEFAULT_PRIVATE_NODE_URLS = Object.freeze(
43549
43609
  native.defaultPrivateNodeUrls()
43550
43610
  );
43551
43611
  var DEFAULT_PRIVATE_BLOCKCHAIN_RID = native.DEFAULT_PRIVATE_BLOCKCHAIN_RID;
43552
- var PUBLIC_CHAIN = {
43553
- network: "public",
43554
- blockchainRid: DEFAULT_BLOCKCHAIN_RID,
43555
- nodeUrls: DEFAULT_CHROMIA_NODE_URLS
43556
- };
43557
43612
  var PRIVATE_CHAIN = {
43558
43613
  network: "private",
43559
43614
  blockchainRid: DEFAULT_PRIVATE_BLOCKCHAIN_RID,
43560
43615
  nodeUrls: DEFAULT_PRIVATE_NODE_URLS
43561
43616
  };
43562
43617
  function chainForNetwork(network) {
43563
- return network === "private" ? PRIVATE_CHAIN : PUBLIC_CHAIN;
43618
+ if (network !== "private") {
43619
+ throw new Error(
43620
+ `network must be "private" (the public chain is retired), got ${JSON.stringify(network)}`
43621
+ );
43622
+ }
43623
+ return PRIVATE_CHAIN;
43564
43624
  }
43565
43625
 
43626
+ // src-ts/constants.ts
43627
+ init_define_ATBASH_DEV_JUDGE_PINS();
43628
+ init_define_ATBASH_PRIVATE_NODE_URLS();
43629
+ init_define_ATBASH_PROD_JUDGE_PINS();
43630
+ var DEFAULT_ENDPOINT = native.DEFAULT_ENDPOINT;
43631
+
43566
43632
  // src-ts/browser/encrypted-toolcall.ts
43567
- init_define_ATBASH_CHROMIA_NODE_URLS();
43633
+ init_define_ATBASH_DEV_JUDGE_PINS();
43568
43634
  init_define_ATBASH_PRIVATE_NODE_URLS();
43635
+ init_define_ATBASH_PROD_JUDGE_PINS();
43569
43636
 
43570
43637
  // src-ts/browser/crypto-ecies.ts
43571
- init_define_ATBASH_CHROMIA_NODE_URLS();
43638
+ init_define_ATBASH_DEV_JUDGE_PINS();
43572
43639
  init_define_ATBASH_PRIVATE_NODE_URLS();
43640
+ init_define_ATBASH_PROD_JUDGE_PINS();
43573
43641
 
43574
43642
  // node_modules/@noble/hashes/hkdf.js
43575
- init_define_ATBASH_CHROMIA_NODE_URLS();
43643
+ init_define_ATBASH_DEV_JUDGE_PINS();
43576
43644
  init_define_ATBASH_PRIVATE_NODE_URLS();
43645
+ init_define_ATBASH_PROD_JUDGE_PINS();
43577
43646
  function extract(hash3, ikm, salt) {
43578
43647
  ahash(hash3);
43579
43648
  if (salt === void 0)
@@ -43614,16 +43683,19 @@ function expand2(hash3, prk, info2, length = 32) {
43614
43683
  var hkdf = (hash3, ikm, salt, info2, length) => expand2(hash3, extract(hash3, ikm, salt), info2, length);
43615
43684
 
43616
43685
  // node_modules/@noble/ciphers/aes.js
43617
- init_define_ATBASH_CHROMIA_NODE_URLS();
43686
+ init_define_ATBASH_DEV_JUDGE_PINS();
43618
43687
  init_define_ATBASH_PRIVATE_NODE_URLS();
43688
+ init_define_ATBASH_PROD_JUDGE_PINS();
43619
43689
 
43620
43690
  // node_modules/@noble/ciphers/_polyval.js
43621
- init_define_ATBASH_CHROMIA_NODE_URLS();
43691
+ init_define_ATBASH_DEV_JUDGE_PINS();
43622
43692
  init_define_ATBASH_PRIVATE_NODE_URLS();
43693
+ init_define_ATBASH_PROD_JUDGE_PINS();
43623
43694
 
43624
43695
  // node_modules/@noble/ciphers/utils.js
43625
- init_define_ATBASH_CHROMIA_NODE_URLS();
43696
+ init_define_ATBASH_DEV_JUDGE_PINS();
43626
43697
  init_define_ATBASH_PRIVATE_NODE_URLS();
43698
+ init_define_ATBASH_PROD_JUDGE_PINS();
43627
43699
  function isBytes3(a) {
43628
43700
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
43629
43701
  }
@@ -44216,8 +44288,9 @@ function encryptedLength(plaintextByteLength) {
44216
44288
  }
44217
44289
 
44218
44290
  // src-ts/crypto/envelope.ts
44219
- init_define_ATBASH_CHROMIA_NODE_URLS();
44291
+ init_define_ATBASH_DEV_JUDGE_PINS();
44220
44292
  init_define_ATBASH_PRIVATE_NODE_URLS();
44293
+ init_define_ATBASH_PROD_JUDGE_PINS();
44221
44294
  var PREFIX = "atb1";
44222
44295
  var SEPARATOR = ".";
44223
44296
  function toBase64(bytes) {
@@ -44350,8 +44423,9 @@ function signEncryptedToolCall(toolCallId, action, context, toolName, toolArgsJs
44350
44423
  }
44351
44424
 
44352
44425
  // src-ts/endpoint.ts
44353
- init_define_ATBASH_CHROMIA_NODE_URLS();
44426
+ init_define_ATBASH_DEV_JUDGE_PINS();
44354
44427
  init_define_ATBASH_PRIVATE_NODE_URLS();
44428
+ init_define_ATBASH_PROD_JUDGE_PINS();
44355
44429
  function buildAllowedJudgeHosts() {
44356
44430
  return /* @__PURE__ */ new Set([
44357
44431
  "atbash.ai",
@@ -44360,6 +44434,30 @@ function buildAllowedJudgeHosts() {
44360
44434
  ]);
44361
44435
  }
44362
44436
  var ALLOWED_JUDGE_HOSTS = buildAllowedJudgeHosts();
44437
+ function isAllowlistedJudgeHost(endpoint) {
44438
+ try {
44439
+ return ALLOWED_JUDGE_HOSTS.has(new URL(endpoint).hostname.toLowerCase());
44440
+ } catch {
44441
+ return false;
44442
+ }
44443
+ }
44444
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
44445
+ var loopbackJudgePins = [];
44446
+ function setLoopbackJudgePinsForTests(keys2) {
44447
+ loopbackJudgePins = keys2.map((k) => k.trim().toLowerCase());
44448
+ }
44449
+ function judgeVerifyKeys(endpoint, configuredKey) {
44450
+ const host = new URL(endpoint).hostname.toLowerCase();
44451
+ const pins = LOOPBACK_HOSTS.has(host) ? loopbackJudgePins : native.pinnedJudgeVerifyKeys(host);
44452
+ const key3 = configuredKey?.trim().toLowerCase();
44453
+ if (pins.length === 0) return key3 ? [key3] : [];
44454
+ if (key3 && !pins.includes(key3)) {
44455
+ throw new Error(
44456
+ `[atbash] verifyPubKey ${key3} is not the response-signing key pinned for ${host}. Refusing to load \u2014 an Atbash host's replies are checked against the key built into the SDK; remove verifyPubKey, or set it to the pinned key.`
44457
+ );
44458
+ }
44459
+ return pins;
44460
+ }
44363
44461
  function validateJudgeEndpoint(judge) {
44364
44462
  const policy = judge?.policy === "self-hosted" ? "self-hosted" : "default";
44365
44463
  const candidate = judge?.endpoint?.trim() || DEFAULT_ENDPOINT;
@@ -44402,18 +44500,31 @@ function validateJudgeEndpoint(judge) {
44402
44500
  }
44403
44501
 
44404
44502
  // src-ts/errors.ts
44405
- init_define_ATBASH_CHROMIA_NODE_URLS();
44503
+ init_define_ATBASH_DEV_JUDGE_PINS();
44406
44504
  init_define_ATBASH_PRIVATE_NODE_URLS();
44505
+ init_define_ATBASH_PROD_JUDGE_PINS();
44407
44506
  var AtbashAPIError = class extends Error {
44408
44507
  /** HTTP status code (or 0 if the request never completed). */
44409
44508
  status;
44410
44509
  /** Raw response body text (may be empty). */
44411
44510
  body;
44412
- constructor(status, body, statusText = "", endpoint = DEFAULT_ENDPOINT) {
44413
- super(enrich(status, body, statusText, endpoint));
44511
+ /**
44512
+ * Request path this status came from, e.g. `/api/v1/judge` — absent when the
44513
+ * request never reached a response (transport failures carry status 0).
44514
+ *
44515
+ * A status alone does not say what failed. Several routes answer one call, and
44516
+ * more than one of them can 404: a caller reading only `404` cannot tell "this
44517
+ * agent is not registered" from "the chain-routing lookup did not resolve", and
44518
+ * has to guess from the body's prose — which a 404 raised before any handler
44519
+ * ran does not carry. The path is the fact that settles it.
44520
+ */
44521
+ path;
44522
+ constructor(status, body, statusText = "", endpoint = DEFAULT_ENDPOINT, path3) {
44523
+ super(enrich(status, body, statusText, endpoint, path3));
44414
44524
  this.name = "AtbashAPIError";
44415
44525
  this.status = status;
44416
44526
  this.body = body;
44527
+ this.path = path3;
44417
44528
  }
44418
44529
  };
44419
44530
  var SignatureVerificationError = class extends Error {
@@ -44422,9 +44533,18 @@ var SignatureVerificationError = class extends Error {
44422
44533
  this.name = "SignatureVerificationError";
44423
44534
  }
44424
44535
  };
44425
- function enrich(status, body, statusText, endpoint) {
44536
+ var JudgeRefusalError = class extends Error {
44537
+ constructor(message) {
44538
+ super(message);
44539
+ this.name = "JudgeRefusalError";
44540
+ }
44541
+ };
44542
+ function isRefusalStatus(status) {
44543
+ return status >= 400 && status < 500 && status !== 408;
44544
+ }
44545
+ function enrich(status, body, statusText, endpoint, path3) {
44426
44546
  const dashboard = endpoint.replace(/\/+$/, "") || DEFAULT_ENDPOINT;
44427
- let msg = `API error ${status}: ${body || statusText}`;
44547
+ let msg = `API error ${status}${path3 ? ` from ${path3}` : ""}: ${body || statusText}`;
44428
44548
  const lowered = body.toLowerCase();
44429
44549
  if (lowered.includes("agent not registered")) {
44430
44550
  msg += `
@@ -44445,9 +44565,68 @@ function enrich(status, body, statusText, endpoint) {
44445
44565
  return msg;
44446
44566
  }
44447
44567
 
44568
+ // src-ts/jail-hold.ts
44569
+ init_define_ATBASH_DEV_JUDGE_PINS();
44570
+ init_define_ATBASH_PRIVATE_NODE_URLS();
44571
+ init_define_ATBASH_PROD_JUDGE_PINS();
44572
+ var DEFAULTS = { ceilingMs: 3e4, pollMs: 1e3 };
44573
+ var holds = /* @__PURE__ */ new Map();
44574
+ var blockedAt = /* @__PURE__ */ new Map();
44575
+ var BLOCK_MEMORY_MS = 10 * 6e4;
44576
+ var config2 = { ...DEFAULTS };
44577
+ function isJailHeld(pubkey) {
44578
+ return holds.has(pubkey);
44579
+ }
44580
+ function recordBlock(pubkey) {
44581
+ const now = performance.now();
44582
+ for (const [key3, at] of blockedAt) if (now - at > BLOCK_MEMORY_MS) blockedAt.delete(key3);
44583
+ blockedAt.set(pubkey, now);
44584
+ }
44585
+ function blockedSince(pubkey, startedAt) {
44586
+ const at = blockedAt.get(pubkey);
44587
+ return at !== void 0 && startedAt <= at;
44588
+ }
44589
+ function holdJail(pubkey, confirmJailed, onGiveUp) {
44590
+ if (holds.has(pubkey)) return;
44591
+ const hold = { timer: null };
44592
+ holds.set(pubkey, hold);
44593
+ const deadline = Date.now() + config2.ceilingMs;
44594
+ const tick = async () => {
44595
+ if (holds.get(pubkey) !== hold) return;
44596
+ let jailed = false;
44597
+ try {
44598
+ jailed = await confirmJailed();
44599
+ } catch {
44600
+ }
44601
+ if (holds.get(pubkey) !== hold) return;
44602
+ if (jailed) {
44603
+ holds.delete(pubkey);
44604
+ return;
44605
+ }
44606
+ if (Date.now() >= deadline) {
44607
+ holds.delete(pubkey);
44608
+ onGiveUp?.();
44609
+ return;
44610
+ }
44611
+ const timer = setTimeout(() => void tick(), config2.pollMs);
44612
+ timer.unref?.();
44613
+ hold.timer = timer;
44614
+ };
44615
+ void tick();
44616
+ }
44617
+ function releaseJailHolds() {
44618
+ for (const hold of holds.values()) if (hold.timer) clearTimeout(hold.timer);
44619
+ holds.clear();
44620
+ blockedAt.clear();
44621
+ }
44622
+ function configureJailHold(next) {
44623
+ config2 = { ...DEFAULTS, ...next };
44624
+ }
44625
+
44448
44626
  // src-ts/http/client.ts
44449
- init_define_ATBASH_CHROMIA_NODE_URLS();
44627
+ init_define_ATBASH_DEV_JUDGE_PINS();
44450
44628
  init_define_ATBASH_PRIVATE_NODE_URLS();
44629
+ init_define_ATBASH_PROD_JUDGE_PINS();
44451
44630
  var HttpClient = class {
44452
44631
  baseUrl;
44453
44632
  timeoutMs;
@@ -44455,8 +44634,8 @@ var HttpClient = class {
44455
44634
  this.baseUrl = baseUrl.replace(/\/+$/, "");
44456
44635
  this.timeoutMs = timeoutMs;
44457
44636
  }
44458
- buildUrl(path4, query) {
44459
- const url = new URL(this.baseUrl + path4);
44637
+ buildUrl(path3, query) {
44638
+ const url = new URL(this.baseUrl + path3);
44460
44639
  if (query) {
44461
44640
  for (const [k, v] of Object.entries(query)) {
44462
44641
  if (v !== void 0 && v !== null && v !== "") {
@@ -44466,14 +44645,14 @@ var HttpClient = class {
44466
44645
  }
44467
44646
  return url.toString();
44468
44647
  }
44469
- async get(path4, query, headers) {
44470
- return this.fetch(this.buildUrl(path4, query), {
44648
+ async get(path3, query, headers) {
44649
+ return this.fetch(this.buildUrl(path3, query), {
44471
44650
  method: "GET",
44472
44651
  ...headers && { headers }
44473
44652
  });
44474
44653
  }
44475
- async post(path4, body, headers) {
44476
- return this.fetch(this.buildUrl(path4), {
44654
+ async post(path3, body, headers) {
44655
+ return this.fetch(this.buildUrl(path3), {
44477
44656
  method: "POST",
44478
44657
  headers: { "Content-Type": "application/json", ...headers },
44479
44658
  body: JSON.stringify(body)
@@ -44516,6 +44695,13 @@ function classifyTransportError(err, url, method, timeoutMs) {
44516
44695
  { cause: err }
44517
44696
  );
44518
44697
  }
44698
+ if (code2 === "UND_ERR_CONNECT_TIMEOUT") {
44699
+ return new HttpTransportError(
44700
+ "timeout",
44701
+ `${method} ${url} could not establish a connection before the transport deadline \u2014 check the endpoint and network`,
44702
+ { cause: err }
44703
+ );
44704
+ }
44519
44705
  if (code2 === "ENOTFOUND" || code2 === "EAI_AGAIN") {
44520
44706
  return new HttpTransportError(
44521
44707
  "dns",
@@ -44545,8 +44731,9 @@ function classifyTransportError(err, url, method, timeoutMs) {
44545
44731
  }
44546
44732
 
44547
44733
  // src-ts/browser/keyLoader.ts
44548
- init_define_ATBASH_CHROMIA_NODE_URLS();
44734
+ init_define_ATBASH_DEV_JUDGE_PINS();
44549
44735
  init_define_ATBASH_PRIVATE_NODE_URLS();
44736
+ init_define_ATBASH_PROD_JUDGE_PINS();
44550
44737
  var NOT_AVAILABLE = "keyLoader is not available in the browser bundle \u2014 pass `agentKey` explicitly to Atbash.fromConfig or use `new Atbash(privkey, opts)`.";
44551
44738
  function resolveKeyPath(_input) {
44552
44739
  throw new Error(NOT_AVAILABLE);
@@ -44555,19 +44742,38 @@ function loadAgentFromFile(_keyPath) {
44555
44742
  throw new Error(NOT_AVAILABLE);
44556
44743
  }
44557
44744
 
44745
+ // src-ts/decision.ts
44746
+ init_define_ATBASH_DEV_JUDGE_PINS();
44747
+ init_define_ATBASH_PRIVATE_NODE_URLS();
44748
+ init_define_ATBASH_PROD_JUDGE_PINS();
44749
+
44558
44750
  // src-ts/normalize.ts
44559
- init_define_ATBASH_CHROMIA_NODE_URLS();
44751
+ init_define_ATBASH_DEV_JUDGE_PINS();
44560
44752
  init_define_ATBASH_PRIVATE_NODE_URLS();
44753
+ init_define_ATBASH_PROD_JUDGE_PINS();
44754
+ function wireText(raw2, fallback = "") {
44755
+ if (raw2 === null || raw2 === void 0) return fallback;
44756
+ if (typeof raw2 === "object" || typeof raw2 === "function") return fallback;
44757
+ return String(raw2);
44758
+ }
44759
+ function wireNumber(raw2, fallback = 0) {
44760
+ if (raw2 === null || raw2 === void 0) return fallback;
44761
+ if (typeof raw2 === "object" || typeof raw2 === "function") return fallback;
44762
+ return Number(raw2);
44763
+ }
44561
44764
  function normalizeVerdict(raw2) {
44562
44765
  if (raw2 === null || raw2 === void 0) return "No verdict";
44563
- const v = String(raw2).toUpperCase();
44766
+ const v = wireText(raw2).trim().toUpperCase();
44564
44767
  if (v === "ALLOW" || v === "GREEN") return "ALLOW";
44565
44768
  if (v === "HOLD" || v === "YELLOW") return "HOLD";
44566
44769
  if (v === "BLOCK" || v === "RED") return "BLOCK";
44567
44770
  return "HOLD";
44568
44771
  }
44772
+ function normalizeActionType(raw2) {
44773
+ return typeof raw2 === "string" ? raw2.trim().toLowerCase() : "";
44774
+ }
44569
44775
  function normalizeStatus(raw2) {
44570
- const s2 = String(raw2 ?? "").toLowerCase();
44776
+ const s2 = wireText(raw2).toLowerCase();
44571
44777
  if (s2 === "pending" || s2 === "answered" || s2 === "error") return s2;
44572
44778
  return "error";
44573
44779
  }
@@ -44582,9 +44788,139 @@ function pubkeyToHex(val) {
44582
44788
  return "";
44583
44789
  }
44584
44790
 
44791
+ // src-ts/decision.ts
44792
+ function isRecord(value) {
44793
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44794
+ }
44795
+ function allowSignalsPermit(data) {
44796
+ const signals = [];
44797
+ if (Object.hasOwn(data, "allow")) signals.push(data.allow);
44798
+ if (isRecord(data.decision) && Object.hasOwn(data.decision, "allow")) {
44799
+ signals.push(data.decision.allow);
44800
+ }
44801
+ return signals.length === 0 || signals.every((value) => value === true);
44802
+ }
44803
+ function explicitRefusal(data) {
44804
+ let hold = false;
44805
+ for (const source of decisionSources(data)) {
44806
+ const verdict = verdictOf(source);
44807
+ if (verdict === "BLOCK" || verdict === "RED") return "BLOCK";
44808
+ if (verdict === "HOLD" || verdict === "YELLOW") hold = true;
44809
+ const actionType = actionTypeOf(source);
44810
+ if (actionType === "block") return "BLOCK";
44811
+ if (actionType === "hold_for_user_confirm") hold = true;
44812
+ }
44813
+ if (!allowSignalsPermit(data)) return "BLOCK";
44814
+ return hold ? "HOLD" : "";
44815
+ }
44816
+ function decisionSources(data) {
44817
+ return [data, isRecord(data.decision) ? data.decision : {}];
44818
+ }
44819
+ function verdictOf(source) {
44820
+ return typeof source.verdict === "string" ? source.verdict.trim().toUpperCase() : "";
44821
+ }
44822
+ function actionTypeRank(actionType) {
44823
+ if (actionType === "block") return 4;
44824
+ if (actionType === "hold_for_user_confirm") return 3;
44825
+ if (actionType === "") return 1;
44826
+ if (actionType === "allow") return 0;
44827
+ return 2;
44828
+ }
44829
+ function actionTypeOf(source) {
44830
+ let winner = "";
44831
+ for (const key3 of ["action_type", "actionType"]) {
44832
+ const raw2 = source[key3];
44833
+ if (raw2 === void 0 || raw2 === null) continue;
44834
+ const actionType = normalizeActionType(raw2);
44835
+ if (actionTypeRank(actionType) > actionTypeRank(winner)) winner = actionType;
44836
+ }
44837
+ return winner;
44838
+ }
44839
+ function wireActionType(data) {
44840
+ for (const source of decisionSources(data)) {
44841
+ const actionType = actionTypeOf(source);
44842
+ if (actionType !== "") return actionType;
44843
+ }
44844
+ return "";
44845
+ }
44846
+ function isAuditTier(data) {
44847
+ const absentVerdict = data.verdict === null || data.verdict === void 0;
44848
+ return absentVerdict && data.status === "logged";
44849
+ }
44850
+ function isAuditTierBody(data) {
44851
+ return isAuditTier(data);
44852
+ }
44853
+ function canonicalAllow(data) {
44854
+ if (explicitRefusal(data) !== "") return false;
44855
+ const actionType = wireActionType(data);
44856
+ if (actionType && actionType !== "allow") return false;
44857
+ if (isAuditTier(data)) return true;
44858
+ if (typeof data.verdict !== "string") return false;
44859
+ const verdict = data.verdict.trim().toUpperCase();
44860
+ return verdict === "ALLOW" || verdict === "GREEN";
44861
+ }
44862
+
44863
+ // src-ts/opentel/events.ts
44864
+ init_define_ATBASH_DEV_JUDGE_PINS();
44865
+ init_define_ATBASH_PRIVATE_NODE_URLS();
44866
+ init_define_ATBASH_PROD_JUDGE_PINS();
44867
+ var SLOW_MS = 1500;
44868
+ var SUCCESS_SAMPLE_RATE = 10;
44869
+ var logger2 = null;
44870
+ var eventsEnabled = false;
44871
+ var sdkVersion = "";
44872
+ var eventSource = "sdk";
44873
+ var hashAgentKey = null;
44874
+ function eventsOptedOut() {
44875
+ const flag = process.env.ATBASH_TELEMETRY_EVENTS_DISABLED?.trim().toLowerCase();
44876
+ return Boolean(flag && ["1", "true", "yes", "on"].includes(flag));
44877
+ }
44878
+ var SOURCE_SHAPE = /^(?:sdk|cli|plugin:[a-z0-9][a-z0-9._-]{0,31})$/;
44879
+ function configureEvents(next, opts = {}) {
44880
+ logger2 = next;
44881
+ eventsEnabled = next !== null && !eventsOptedOut();
44882
+ if (opts.version) sdkVersion = opts.version;
44883
+ if (opts.source && SOURCE_SHAPE.test(opts.source)) eventSource = opts.source;
44884
+ hashAgentKey = opts.hashAgentKey ?? null;
44885
+ }
44886
+ function eventsAreOn() {
44887
+ return eventsEnabled && logger2 !== null;
44888
+ }
44889
+ function sampleRateFor(e) {
44890
+ if (e.status === "error") return 1;
44891
+ if (e.durationMs >= SLOW_MS) return 1;
44892
+ return Math.random() < 1 / SUCCESS_SAMPLE_RATE ? SUCCESS_SAMPLE_RATE : 0;
44893
+ }
44894
+ function recordEvent(e) {
44895
+ if (!eventsAreOn()) return;
44896
+ const sampleRate = sampleRateFor(e);
44897
+ if (sampleRate === 0) return;
44898
+ try {
44899
+ const attributes = {
44900
+ "function.name": e.functionName,
44901
+ "duration_ms": Math.round(e.durationMs),
44902
+ status: e.status,
44903
+ source: eventSource,
44904
+ // Honeycomb reweights counts and percentiles by this. It is per-event
44905
+ // because the sampling is biased by outcome and latency.
44906
+ sampleRate
44907
+ };
44908
+ if (sdkVersion) attributes["sdk.version"] = sdkVersion;
44909
+ if (e.agentPubkey && hashAgentKey) attributes["agent.hash"] = hashAgentKey(e.agentPubkey);
44910
+ if (e.chain) attributes["chain"] = e.chain;
44911
+ if (e.errorClass) attributes["error.class"] = e.errorClass;
44912
+ if (e.errorStatus !== void 0) attributes["error.status"] = e.errorStatus;
44913
+ if (e.errorPath) attributes["error.path"] = e.errorPath;
44914
+ if (e.outcome) attributes["outcome"] = e.outcome;
44915
+ logger2.emit({ body: e.functionName, attributes });
44916
+ } catch {
44917
+ }
44918
+ }
44919
+
44585
44920
  // src-ts/browser/opentel/telemetry.ts
44586
- init_define_ATBASH_CHROMIA_NODE_URLS();
44921
+ init_define_ATBASH_DEV_JUDGE_PINS();
44587
44922
  init_define_ATBASH_PRIVATE_NODE_URLS();
44923
+ init_define_ATBASH_PROD_JUDGE_PINS();
44588
44924
  function setupTelemetry(_config) {
44589
44925
  }
44590
44926
  function recordCall(_functionName, _source, _agentPubkey) {
@@ -44597,8 +44933,9 @@ async function shutdownTelemetry() {
44597
44933
  }
44598
44934
 
44599
44935
  // src-ts/browser/userConfig.ts
44600
- init_define_ATBASH_CHROMIA_NODE_URLS();
44936
+ init_define_ATBASH_DEV_JUDGE_PINS();
44601
44937
  init_define_ATBASH_PRIVATE_NODE_URLS();
44938
+ init_define_ATBASH_PROD_JUDGE_PINS();
44602
44939
  var NOT_AVAILABLE2 = "userConfig file I/O is not available in the browser bundle.";
44603
44940
  function getConfigDir() {
44604
44941
  throw new Error(NOT_AVAILABLE2);
@@ -44616,13 +44953,21 @@ function resolve(_key, flagValue) {
44616
44953
  return flagValue ?? "";
44617
44954
  }
44618
44955
  function forcedChainNetwork(flagValue) {
44619
- return flagValue === "public" || flagValue === "private" ? flagValue : void 0;
44956
+ return flagValue === "private" ? flagValue : void 0;
44620
44957
  }
44621
- function warnDeprecatedEnvVarsOnce(_log) {
44958
+ function agentKeyFromEnv() {
44959
+ return "";
44960
+ }
44961
+ function strandedAgentKey() {
44962
+ return "";
44622
44963
  }
44623
44964
 
44624
44965
  // src-ts/client.ts
44966
+ var AGENT_NOT_REGISTERED = "Agent not registered. Onboard the agent at the dashboard before submitting actions.";
44967
+ var TOOL_CALL_IDS_FOR_TESTS = /* @__PURE__ */ Symbol.for("@atbash/sdk.toolCallIdsForTests");
44625
44968
  function generateToolCallId() {
44969
+ const fixed = globalThis[TOOL_CALL_IDS_FOR_TESTS];
44970
+ if (fixed && fixed.ids.length > 0) return fixed.ids[fixed.next++ % fixed.ids.length];
44626
44971
  return `tc-${Date.now()}-${randomHex(4)}`;
44627
44972
  }
44628
44973
  function resolveConstructorChain(options) {
@@ -44631,20 +44976,25 @@ function resolveConstructorChain(options) {
44631
44976
  const hasBrid = options.blockchainRid !== void 0;
44632
44977
  if (hasNodeUrls !== hasBrid) {
44633
44978
  throw new Error(
44634
- 'nodeUrls and blockchainRid must be provided together \u2014 passing one without the other 404s every chain request. Prefer `chain: PUBLIC_CHAIN | PRIVATE_CHAIN` or `network: "public" | "private"`.'
44979
+ 'nodeUrls and blockchainRid must be provided together \u2014 passing one without the other 404s every chain request. Prefer `chain: PRIVATE_CHAIN` or `network: "private"`.'
44635
44980
  );
44636
44981
  }
44637
44982
  if (hasNodeUrls && hasBrid) {
44638
- const brid = options.blockchainRid;
44639
- const derivedNetwork = options.network ?? (brid === PUBLIC_CHAIN.blockchainRid ? "public" : brid === PRIVATE_CHAIN.blockchainRid ? "private" : "private");
44640
44983
  return {
44641
- network: derivedNetwork,
44642
- blockchainRid: brid,
44984
+ network: "private",
44985
+ blockchainRid: options.blockchainRid,
44643
44986
  nodeUrls: options.nodeUrls
44644
44987
  };
44645
44988
  }
44646
44989
  return chainForNetwork(options.network ?? forcedChainNetwork() ?? "private");
44647
44990
  }
44991
+ function errorDetail(err) {
44992
+ if (!(err instanceof AtbashAPIError)) return {};
44993
+ return {
44994
+ errorStatus: err.status,
44995
+ ...err.path ? { errorPath: err.path } : {}
44996
+ };
44997
+ }
44648
44998
  var Atbash = class _Atbash {
44649
44999
  auth;
44650
45000
  endpoint;
@@ -44654,10 +45004,23 @@ var Atbash = class _Atbash {
44654
45004
  orgName;
44655
45005
  /** Default judge response-signing pubkey, if configured (see fromConfig). */
44656
45006
  verifyPubKey;
45007
+ /**
45008
+ * The keys every judge reply must be signed by: the host's pinned keys, or
45009
+ * the configured `verifyPubKey` on a host with none. Empty means unchecked.
45010
+ */
45011
+ verifyKeys;
44657
45012
  /** Default org encryption key — see {@link AtbashOptions.orgEncryptionPubKey}. */
44658
45013
  orgEncryptionPubKey;
44659
45014
  /** When true (default), `auditToolCall` denies on any error. */
44660
45015
  failClosed;
45016
+ /** When true (default), an unenforced (audit-tier) answer is refused. */
45017
+ requireEnforcement;
45018
+ /** When true, a signed non-enforcing mode never relaxes a verdict. */
45019
+ enforceLocally;
45020
+ /** Results whose enforcement mode came signed and bound to their call. */
45021
+ modeTrusted = /* @__PURE__ */ new WeakSet();
45022
+ /** Overall deadline for one auditToolCall decision, in ms. */
45023
+ decisionTimeoutMs;
44661
45024
  /** Org key learned from the last agent-exists check, for this agent only. */
44662
45025
  _orgKeyFromChain = null;
44663
45026
  debug;
@@ -44699,16 +45062,6 @@ var Atbash = class _Atbash {
44699
45062
  */
44700
45063
  _agentExistsCache = null;
44701
45064
  static AGENT_EXISTS_TTL_MS = 5e3;
44702
- /**
44703
- * Cached bearer token for risk-engine / insurance read calls. Built
44704
- * lazily as a signed `log_tool_call` tx and refreshed every 4 min so
44705
- * server-side replay protection windows never expire it mid-session.
44706
- */
44707
- // Keyed by blockchainRid so bearers for the public and private chains can
44708
- // coexist. The dashboard derives `authNetwork` from the BRID inside the
44709
- // signed envelope, so a bearer signed for chain A cannot authenticate a
44710
- // request routed to chain B — every chain the client talks to needs its own.
44711
- _authBearers = /* @__PURE__ */ new Map();
44712
45065
  /** Guards `logEnvironmentOnce` — hosts construct several clients. */
44713
45066
  static environmentLogged = false;
44714
45067
  constructor(privkey, options = {}) {
@@ -44727,30 +45080,42 @@ var Atbash = class _Atbash {
44727
45080
  this._defaultChain = resolvedChain;
44728
45081
  this._explicitChain = options.chain !== void 0 || options.network !== void 0 || options.blockchainRid !== void 0 && options.nodeUrls !== void 0;
44729
45082
  this._forcedNetwork = forcedChainNetwork();
44730
- warnDeprecatedEnvVarsOnce((msg) => options.logger?.warn?.(msg));
44731
45083
  this.orgName = options.orgName;
44732
45084
  this.verifyPubKey = validated.verifyPubKey ?? void 0;
45085
+ this.verifyKeys = judgeVerifyKeys(this.endpoint, this.verifyPubKey);
44733
45086
  this.orgEncryptionPubKey = options.orgEncryptionPubKey;
44734
45087
  this.failClosed = options.failClosed !== false;
45088
+ this.requireEnforcement = options.requireEnforcement !== false;
45089
+ this.enforceLocally = options.enforceLocally === true;
45090
+ this.decisionTimeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
44735
45091
  this.debug = options.debug === true;
44736
45092
  this.logger = options.logger ?? {};
44737
- this.http = new HttpClient(this.endpoint, options.timeoutMs ?? 6e4);
45093
+ this.http = new HttpClient(this.endpoint, options.timeoutMs ?? 12e4);
44738
45094
  this.logEnvironmentOnce();
44739
45095
  if (this.endpoint !== DEFAULT_ENDPOINT) {
44740
45096
  this.logger.warn?.("[atbash] running on non-default judge endpoint", {
44741
45097
  endpoint: this.endpoint,
44742
- verifying: this.verifyPubKey ? "with response-signature pubkey configured" : "without signature verification"
45098
+ verifying: this.verifyKeys.length > 0 ? "with response-signature pubkey configured" : "without signature verification"
44743
45099
  });
44744
45100
  }
44745
- try {
44746
- setupTelemetry({
44747
- enabled: true,
44748
- source: "sdk",
44749
- endpoint: this.endpoint,
44750
- getAuthHeaders: () => this.authHeaders()
44751
- });
44752
- } catch (err) {
44753
- this.logger.warn?.("[atbash] telemetry setup failed \u2014 continuing without metrics", { error: String(err) });
45101
+ if (isAllowlistedJudgeHost(this.endpoint)) {
45102
+ try {
45103
+ setupTelemetry({
45104
+ enabled: true,
45105
+ endpoint: this.endpoint,
45106
+ getAuthHeaders: () => this.authHeaders()
45107
+ });
45108
+ } catch (err) {
45109
+ this.logger.warn?.(
45110
+ "[atbash] telemetry setup failed \u2014 continuing without metrics",
45111
+ { error: String(err) }
45112
+ );
45113
+ }
45114
+ } else {
45115
+ this.logger.info?.(
45116
+ "[atbash] telemetry disabled \u2014 the agent bearer is only sent to hosts that already receive it, and this judge endpoint is not one",
45117
+ { endpoint: this.endpoint }
45118
+ );
44754
45119
  }
44755
45120
  }
44756
45121
  /**
@@ -44768,13 +45133,12 @@ var Atbash = class _Atbash {
44768
45133
  _Atbash.environmentLogged = true;
44769
45134
  const brief = (rid) => rid ? `${rid.slice(0, 8)}\u2026` : "(unset)";
44770
45135
  this.logger.info?.(
44771
- `[atbash] environment \u2014 judge=${this.endpoint} publicChain=${brief(native.DEFAULT_BLOCKCHAIN_RID)} privateChain=${brief(native.DEFAULT_PRIVATE_BLOCKCHAIN_RID)} activeChain=${brief(this.blockchainRid)} responseSignatureCheck=${this.verifyPubKey ? "on" : "off"}`,
45136
+ `[atbash] environment \u2014 judge=${this.endpoint} privateChain=${brief(native.DEFAULT_PRIVATE_BLOCKCHAIN_RID)} activeChain=${brief(this.blockchainRid)} responseSignatureCheck=${this.verifyKeys.length > 0 ? "on" : "off"}`,
44772
45137
  {
44773
45138
  judgeEndpoint: this.endpoint,
44774
- publicBlockchainRid: native.DEFAULT_BLOCKCHAIN_RID,
44775
45139
  privateBlockchainRid: native.DEFAULT_PRIVATE_BLOCKCHAIN_RID,
44776
45140
  activeBlockchainRid: this.blockchainRid,
44777
- responseSignatureCheck: Boolean(this.verifyPubKey)
45141
+ responseSignatureCheck: this.verifyKeys.length > 0
44778
45142
  }
44779
45143
  );
44780
45144
  }
@@ -44786,6 +45150,84 @@ var Atbash = class _Atbash {
44786
45150
  * validated against the trusted allowlist / self-hosted policy; a
44787
45151
  * self-hosted endpoint's `verifyPubKey` becomes the client default.
44788
45152
  */
45153
+ /**
45154
+ * Decide which key this client signs as.
45155
+ *
45156
+ * Most specific wins: a key passed in code, then a key file the host named,
45157
+ * then the environment, then the default key file. `config.json` is absent
45158
+ * from that list on purpose — it is a settings file, writable by anything
45159
+ * that can write the user's home and read by every Atbash integration on the
45160
+ * machine, so letting it name the key meant one stray value silently
45161
+ * re-pointed who each of them signed as.
45162
+ *
45163
+ * A named `keyPath` that does not exist throws rather than falling through.
45164
+ * The caller said which file holds its identity; quietly signing as a
45165
+ * different one is the outcome worth refusing.
45166
+ *
45167
+ * @param options - The `fromConfig` options, read for `agentKey` and `keyPath`.
45168
+ * @returns The resolved agent identity.
45169
+ * @throws When a named key file is missing, or no identity can be found.
45170
+ */
45171
+ static resolveIdentity(options) {
45172
+ if (options.agentKey) return native.loadAgent(options.agentKey);
45173
+ if (options.keyPath) return loadAgentFromFile(options.keyPath);
45174
+ const fromEnv = agentKeyFromEnv();
45175
+ if (fromEnv) return native.loadAgent(fromEnv);
45176
+ try {
45177
+ return loadAgentFromFile();
45178
+ } catch (err) {
45179
+ throw _Atbash.explainStrandedKey(err);
45180
+ }
45181
+ }
45182
+ /**
45183
+ * Add the one thing a machine with no key file needs to hear.
45184
+ *
45185
+ * This is the only path where the operator cannot see what happened: no key
45186
+ * file, and the key they are looking for sits in `config.json`, which no
45187
+ * longer selects the identity. A bare "key file not found" sends them hunting
45188
+ * for a key they already have. Only this branch gets the hint — a caller who
45189
+ * named a `keyPath` is told about that path, where a stranded key is noise.
45190
+ *
45191
+ * @param err - The "key file not found" error from the default lookup.
45192
+ * @returns The same error, or one that also names the key in config.json.
45193
+ */
45194
+ static explainStrandedKey(err) {
45195
+ const stranded = strandedAgentKey();
45196
+ if (!stranded) return err;
45197
+ let identity;
45198
+ try {
45199
+ identity = native.derivePublicKey(stranded);
45200
+ } catch {
45201
+ identity = "(unreadable)";
45202
+ }
45203
+ const message = err instanceof Error ? err.message : String(err);
45204
+ return new Error(
45205
+ `${message}
45206
+ config.json still holds an "agentKey" (${identity}), but a settings file no longer chooses the signing key. Move it into one of the key files above, or set ATBASH_AGENT_KEY.`
45207
+ );
45208
+ }
45209
+ /**
45210
+ * Say so when `config.json` still holds an agent key.
45211
+ *
45212
+ * Nothing signs with it any more, and silence would leave an operator
45213
+ * believing one identity is in force while another is. The pubkey is named,
45214
+ * not the key, so the line is safe in a log.
45215
+ *
45216
+ * @param logger - The host logger, when one was supplied.
45217
+ */
45218
+ static warnOnStrandedKey(logger3) {
45219
+ const stranded = strandedAgentKey();
45220
+ if (!stranded) return;
45221
+ let identity;
45222
+ try {
45223
+ identity = native.derivePublicKey(stranded);
45224
+ } catch {
45225
+ identity = "(unreadable)";
45226
+ }
45227
+ logger3?.warn?.(
45228
+ `[atbash] "agentKey" in config.json is ignored \u2014 settings do not choose the signing key. It holds ${identity}; this client signs as the key file or ATBASH_AGENT_KEY instead. Move it into the key file, or delete the field, to silence this.`
45229
+ );
45230
+ }
44789
45231
  static fromConfig(options = {}) {
44790
45232
  const configuredEndpoint = resolve("judgeEndpoint") || void 0;
44791
45233
  const configuredVerifyPubKey = resolve("judgeVerifyPubKey") || void 0;
@@ -44801,8 +45243,8 @@ var Atbash = class _Atbash {
44801
45243
  verifyPubKey: configuredVerifyPubKey
44802
45244
  } : { endpoint: configuredEndpoint })
44803
45245
  );
44804
- const agentKey = resolve("agentKey", options.agentKey);
44805
- const auth = agentKey ? native.loadAgent(agentKey) : loadAgentFromFile(options.keyPath);
45246
+ const auth = _Atbash.resolveIdentity(options);
45247
+ _Atbash.warnOnStrandedKey(options.logger);
44806
45248
  return new _Atbash(auth.privkey, {
44807
45249
  endpoint: validated.url,
44808
45250
  chain: options.chain,
@@ -44813,6 +45255,9 @@ var Atbash = class _Atbash {
44813
45255
  orgName: options.orgName,
44814
45256
  verifyPubKey: validated.verifyPubKey ?? void 0,
44815
45257
  failClosed: options.failClosed,
45258
+ requireEnforcement: options.requireEnforcement,
45259
+ enforceLocally: options.enforceLocally,
45260
+ decisionTimeoutMs: options.decisionTimeoutMs,
44816
45261
  // ATBASH_DEBUG lets an operator turn diagnostics on without editing a
44817
45262
  // host's plugin config, which is usually the harder half.
44818
45263
  debug: options.debug ?? /^(1|true|yes)$/i.test(resolve("debug")),
@@ -44879,6 +45324,15 @@ var Atbash = class _Atbash {
44879
45324
  * return the signed tx hex. The server broadcasts to chain.
44880
45325
  */
44881
45326
  async logToolCall(action, context = "", options = {}) {
45327
+ return this._logToolCall(action, context, options, false);
45328
+ }
45329
+ /**
45330
+ * `raisePreflightErrors` (the judge path, like Python's
45331
+ * `raise_preflight_errors`): a failed registration check throws instead of
45332
+ * becoming `{ success: false }`, so the caller can tell Atbash's "no"
45333
+ * (not registered, or a 4xx) from an outage.
45334
+ */
45335
+ async _logToolCall(action, context, options, raisePreflightErrors) {
44882
45336
  const start = performance.now();
44883
45337
  recordCall("logToolCall", void 0, this.auth.pubkey);
44884
45338
  let exists;
@@ -44888,18 +45342,20 @@ var Atbash = class _Atbash {
44888
45342
  });
44889
45343
  } catch (err) {
44890
45344
  recordDuration("logToolCall", performance.now() - start, "error");
45345
+ if (raisePreflightErrors) throw err;
44891
45346
  return { success: false, toolCallId: null, error: errorMessage(err) };
44892
45347
  }
44893
45348
  if (!exists) {
44894
45349
  recordDuration("logToolCall", performance.now() - start, "error");
45350
+ if (raisePreflightErrors) throw new JudgeRefusalError(AGENT_NOT_REGISTERED);
44895
45351
  return {
44896
45352
  success: false,
44897
45353
  toolCallId: null,
44898
- error: "Agent not registered. Onboard the agent at the dashboard before submitting actions."
45354
+ error: AGENT_NOT_REGISTERED
44899
45355
  };
44900
45356
  }
44901
45357
  const toolCallId = generateToolCallId();
44902
- const brid = options.chainOpts?.blockchainRid || options.chainOpts?.network ? this.bridFromChainOpts(options.chainOpts) : await this.defaultOrgBrid() ?? this.blockchainRid;
45358
+ const brid = await this.callBrid(options.chainOpts);
44903
45359
  const orgKey = options.orgEncryptionPubKey ?? this.orgEncryptionPubKey ?? this._orgKeyFromChain;
44904
45360
  try {
44905
45361
  const signedHex = orgKey ? signEncryptedToolCall(
@@ -44935,23 +45391,39 @@ var Atbash = class _Atbash {
44935
45391
  * response bytes via the Rust core's `verifySignature`.
44936
45392
  */
44937
45393
  async judgeAction(action, context = "", options = {}) {
45394
+ return this.judgeTracked(action, context, options, false);
45395
+ }
45396
+ /**
45397
+ * judgeAction, optionally asking the judge for the true verdict and the
45398
+ * organisation's enforcement mode so this client applies the mode itself.
45399
+ *
45400
+ * Only auditToolCall opts in: judgeAction's callers keep the server-side
45401
+ * downgrade they gate on today.
45402
+ *
45403
+ * @param clientEnforces - Send `X-Atbash-Client-Enforcement` when the reply can be trusted.
45404
+ */
45405
+ judgeTracked(action, context, options, clientEnforces) {
44938
45406
  return this.track("judgeAction", this.auth.pubkey, async () => {
44939
45407
  try {
44940
- return await this._judgeAction(action, context, options);
45408
+ return await this._judgeAction(action, context, options, clientEnforces);
44941
45409
  } catch (err) {
44942
45410
  if (!isEncryptionStateMismatch(err)) throw err;
44943
45411
  this._orgKeyFromChain = null;
44944
- return await this._judgeAction(action, context, options);
45412
+ return await this._judgeAction(action, context, options, clientEnforces);
44945
45413
  }
44946
45414
  });
44947
45415
  }
44948
- async _judgeAction(action, context, options) {
45416
+ async _judgeAction(action, context, options, clientEnforces = false) {
44949
45417
  if (!action?.trim()) {
44950
45418
  throw new Error("action is required and cannot be empty.");
44951
45419
  }
45420
+ if (isJailHeld(this.auth.pubkey)) return this.localJailBlock();
45421
+ const startedAt = performance.now();
44952
45422
  let chainOpts = options.chainOpts;
44953
45423
  if (options.orgName && this._explicitChain) {
44954
- chainOpts = options.chainOpts ?? { network: this._defaultChain.network };
45424
+ chainOpts = options.chainOpts ?? {
45425
+ blockchainRid: this._defaultChain.blockchainRid
45426
+ };
44955
45427
  } else if (options.orgName && this.forcedNetwork()) {
44956
45428
  chainOpts = { network: this.forcedNetwork() };
44957
45429
  } else if (options.orgName) {
@@ -44961,36 +45433,36 @@ var Atbash = class _Atbash {
44961
45433
  } else {
44962
45434
  const mapNetwork = await this.getActiveNetworkForOrg(options.orgName);
44963
45435
  if (mapNetwork) {
44964
- const chain = mapNetwork === "private" ? PRIVATE_CHAIN : PUBLIC_CHAIN;
44965
- this._chainCache.set(options.orgName, chain);
45436
+ this._chainCache.set(options.orgName, chainForNetwork(mapNetwork));
44966
45437
  chainOpts = { network: mapNetwork };
44967
45438
  } else if (!chainOpts?.blockchainRid) {
44968
- const resolved = await this.resolveChainFromMap(options.orgName, null);
45439
+ const resolved = await this.resolveChainFromMap(
45440
+ options.orgName,
45441
+ null
45442
+ );
44969
45443
  chainOpts = { ...chainOpts, network: resolved.network };
44970
45444
  }
44971
45445
  }
44972
45446
  }
44973
- const brid = this.bridFromChainOpts(chainOpts);
44974
- const logResult = await this.logToolCall(action, context, {
44975
- toolName: options.toolName,
44976
- toolArgsJson: options.toolArgsJson,
44977
- chainOpts
44978
- });
45447
+ const brid = await this.callBrid(chainOpts);
45448
+ const logResult = await this._logToolCall(
45449
+ action,
45450
+ context,
45451
+ { toolName: options.toolName, toolArgsJson: options.toolArgsJson, chainOpts },
45452
+ true
45453
+ );
44979
45454
  if (!logResult.success || !logResult.toolCallId || !logResult.signedHex) {
44980
45455
  throw new Error(logResult.error || "Failed to sign log_tool_call");
44981
45456
  }
44982
- let signedJudgeAction;
44983
- if (!options.provider) {
44984
- const judgmentId = generateToolCallId();
44985
- signedJudgeAction = native.signJudgeAction(
44986
- judgmentId,
44987
- action,
44988
- context || "",
44989
- "",
44990
- this.auth.privkey,
44991
- brid
44992
- );
44993
- }
45457
+ const judgmentId = generateToolCallId();
45458
+ const signedJudgeAction = native.signJudgeAction(
45459
+ judgmentId,
45460
+ action,
45461
+ context || "",
45462
+ "",
45463
+ this.auth.privkey,
45464
+ brid
45465
+ );
44994
45466
  const body = {
44995
45467
  tool_call_id: logResult.toolCallId,
44996
45468
  agent_pubkey: this.auth.pubkey,
@@ -44999,58 +45471,132 @@ var Atbash = class _Atbash {
44999
45471
  };
45000
45472
  if (signedJudgeAction) body.signed_judge_action = signedJudgeAction;
45001
45473
  if (context) body.context = context;
45002
- if (options.provider) body.provider = options.provider;
45003
45474
  if (options.toolName) body.tool_name = options.toolName;
45004
45475
  if (options.toolArgsJson) body.tool_args_json = options.toolArgsJson;
45005
- if (options.model) body.model = options.model;
45006
45476
  if (options.resolved) body.resolved = options.resolved;
45007
45477
  if (options.mode) body.mode = options.mode;
45478
+ const verifyKeys = this.effectiveVerifyKeys(options.verifyPubKey);
45479
+ const optIn = clientEnforces && (verifyKeys.length > 0 || this.enforceLocally);
45480
+ const optInValue = this.enforceLocally ? "strict" : "1";
45008
45481
  let resp;
45009
45482
  try {
45010
- resp = await this.http.post("/api/v1/judge", body);
45483
+ resp = await this.http.post(
45484
+ "/api/v1/judge",
45485
+ body,
45486
+ optIn ? { "X-Atbash-Client-Enforcement": optInValue } : void 0
45487
+ );
45011
45488
  } catch (err) {
45012
45489
  throw this.transportError(err);
45013
45490
  }
45014
45491
  if (!resp.ok) throw await this.httpError(resp);
45015
45492
  const bodyBytes = Buffer.from(await resp.arrayBuffer());
45016
- const verifyPubKey = options.verifyPubKey ?? this.verifyPubKey;
45017
- if (verifyPubKey !== void 0) {
45018
- const sig = resp.headers.get("X-Atbash-Signature");
45019
- if (!sig) {
45493
+ if (verifyKeys.length > 0) {
45494
+ verifyResponseSignature(bodyBytes, resp, verifyKeys);
45495
+ }
45496
+ const parsed = tryParseJson(bodyBytes.toString("utf-8"));
45497
+ if (!isRecord2(parsed)) {
45498
+ throw new JudgeRefusalError(
45499
+ "The judge's reply could not be read, so the action was not approved."
45500
+ );
45501
+ }
45502
+ const data = parsed;
45503
+ const rawScore = data.score;
45504
+ const score = typeof rawScore === "number" && Number.isInteger(rawScore) && rawScore >= 1 && rawScore <= 10 ? rawScore : void 0;
45505
+ const statedId = wireText(data.tool_call_id);
45506
+ const statedJudgment = wireText(data.judgment_id);
45507
+ const statedStatus = wireText(data.on_chain_status);
45508
+ const statedJudgeStatus = typeof data.status === "string" ? data.status : "";
45509
+ const boundToCall = (statedId === logResult.toolCallId || statedId === judgmentId) && (!statedJudgment || statedJudgment === judgmentId);
45510
+ const signatureChecked = verifyKeys.length > 0;
45511
+ const result = {
45512
+ verdict: normalizeVerdict(data.verdict),
45513
+ allow: this.executable(data),
45514
+ actionType: normalizeActionType(data.action_type),
45515
+ reason: wireText(data.reason),
45516
+ confidence: wireNumber(data.confidence),
45517
+ provider: wireText(data.provider),
45518
+ latencyMs: wireNumber(data.latency_ms),
45519
+ toolCallId: wireText(data.tool_call_id, logResult.toolCallId),
45520
+ ...wireText(data.judgment_id) ? { judgmentId: wireText(data.judgment_id) } : {},
45521
+ onChain: Boolean(data.on_chain),
45522
+ // Only a stated boolean is a statement: `onChain` above reads silence as false.
45523
+ ...typeof data.on_chain === "boolean" ? {
45524
+ record: {
45525
+ onChain: data.on_chain,
45526
+ ...statedStatus ? { status: statedStatus } : {},
45527
+ boundToCall,
45528
+ signatureChecked,
45529
+ ...statedJudgeStatus ? { judgeStatus: statedJudgeStatus } : {},
45530
+ // A judge status marks a reply that carries no verdict: a shadow
45531
+ // ack, or an answer that was only logged.
45532
+ verdictRecorded: data.on_chain && boundToCall && signatureChecked && !statedJudgeStatus
45533
+ }
45534
+ } : {},
45535
+ enforced: Boolean(data.enforced),
45536
+ enforcementMode: wireText(data.enforcement_mode),
45537
+ status: wireText(data.status),
45538
+ score,
45539
+ refusal: explicitRefusal(data)
45540
+ };
45541
+ if (optIn) {
45542
+ const echo = data.client_enforcement;
45543
+ if (echo !== void 0 && echo !== optInValue || echo === void 0 && this.enforceLocally) {
45020
45544
  throw new SignatureVerificationError(
45021
- "missing X-Atbash-Signature header"
45545
+ "the reply does not confirm the enforcement this client asked for"
45022
45546
  );
45023
45547
  }
45024
- let ok;
45025
- try {
45026
- ok = native.verifySignature(bodyBytes, sig, verifyPubKey);
45027
- } catch (err) {
45028
- throw new SignatureVerificationError(
45029
- `signature verification threw: ${errorMessage(err)}`
45030
- );
45548
+ if (verifyKeys.length > 0) {
45549
+ if (statedId && statedId !== logResult.toolCallId && statedId !== judgmentId || statedJudgment && statedJudgment !== judgmentId) {
45550
+ throw new SignatureVerificationError(
45551
+ `the signed reply is for call ${statedJudgment || statedId}, not this one`
45552
+ );
45553
+ }
45554
+ if (statedId && echo === optInValue) this.modeTrusted.add(result);
45031
45555
  }
45032
- if (!ok) {
45033
- throw new SignatureVerificationError(
45034
- "signature does not verify against configured verifyPubKey"
45556
+ }
45557
+ return this.applyJailHold(result, startedAt, statedStatus);
45558
+ }
45559
+ /**
45560
+ * Start a local hold on an enforced BLOCK that jails: one already on chain,
45561
+ * or one the judge answered before its chain write landed
45562
+ * (`on_chain_status: "pending"`), which jails once it lands. Refuse any other
45563
+ * result that lands while the agent is held, or whose request was already in
45564
+ * flight when the block arrived: the server judged it on pre-jail state.
45565
+ *
45566
+ * @param onChainStatus - The reply's `on_chain_status`; empty when absent.
45567
+ */
45568
+ applyJailHold(result, startedAt, onChainStatus = "") {
45569
+ const pubkey = this.auth.pubkey;
45570
+ if (result.verdict === "BLOCK" && result.enforced) {
45571
+ recordBlock(pubkey);
45572
+ if (result.onChain || onChainStatus === "pending") {
45573
+ holdJail(
45574
+ pubkey,
45575
+ () => this.getAgentPolicy(pubkey).then((p) => p.isJailed),
45576
+ () => this.logger.warn?.("[atbash] local jail hold released: the chain did not confirm the jail in time")
45035
45577
  );
45036
45578
  }
45579
+ return result;
45037
45580
  }
45038
- const data = parseJson(bodyBytes);
45039
- const rawScore = data.score;
45040
- const score = typeof rawScore === "number" && Number.isInteger(rawScore) && rawScore >= 1 && rawScore <= 10 ? rawScore : void 0;
45581
+ return isJailHeld(pubkey) || blockedSince(pubkey, startedAt) ? this.localJailBlock(result.toolCallId) : result;
45582
+ }
45583
+ /** The server's jailed refusal, produced locally while the agent is held. */
45584
+ localJailBlock(toolCallId = generateToolCallId()) {
45041
45585
  return {
45042
- verdict: normalizeVerdict(data.verdict),
45043
- actionType: String(data.action_type ?? ""),
45044
- reason: String(data.reason ?? ""),
45045
- confidence: Number(data.confidence ?? 0),
45046
- provider: String(data.provider ?? ""),
45047
- latencyMs: Number(data.latency_ms ?? 0),
45048
- toolCallId: String(data.tool_call_id ?? logResult.toolCallId),
45049
- onChain: Boolean(data.on_chain),
45050
- enforced: Boolean(data.enforced),
45051
- enforcementMode: String(data.enforcement_mode ?? ""),
45052
- status: String(data.status ?? ""),
45053
- score
45586
+ verdict: "BLOCK",
45587
+ allow: false,
45588
+ actionType: "block",
45589
+ reason: `Agent is jailed. All actions are blocked until the organization owner unjails this agent at ${this.endpoint.replace(/\/+$/, "")}/risk-engine/agents.`,
45590
+ confidence: 1,
45591
+ provider: "policy",
45592
+ latencyMs: 0,
45593
+ toolCallId,
45594
+ onChain: false,
45595
+ enforced: true,
45596
+ enforcementMode: "enforce",
45597
+ status: "",
45598
+ score: void 0,
45599
+ refusal: "BLOCK"
45054
45600
  };
45055
45601
  }
45056
45602
  /* ── audit_tool_call (redact → judge → decision) ───────────────────────── */
@@ -45083,77 +45629,193 @@ var Atbash = class _Atbash {
45083
45629
  }
45084
45630
  try {
45085
45631
  this.logger.info?.("[atbash] judge API called", { tool: toolName });
45086
- const result = await this.judgeAction(actionText, contextText, {
45087
- toolName,
45088
- toolArgsJson: argsJson,
45089
- orgName: this.orgName,
45090
- // Passed through unredacted — caller vouches for the contents.
45091
- resolved: input.resolved
45092
- });
45093
- if (result.verdict === "No verdict") {
45094
- if (result.status !== "logged") {
45095
- return this.failJudge(
45096
- `judge returned no verdict without an audit-tier marker (status: ${result.status || "absent"})`,
45097
- void 0,
45098
- result.toolCallId
45099
- );
45100
- }
45101
- return {
45102
- allow: true,
45103
- verdict: "ALLOW",
45104
- reason: result.reason || "audit tier \u2014 request logged on-chain, no AI enforcement",
45105
- toolCallId: result.toolCallId
45106
- };
45107
- }
45108
- const action = result.actionType;
45109
- if (action === "block") {
45632
+ const result = await withDeadline(
45633
+ this.judgeTracked(
45634
+ actionText,
45635
+ contextText,
45636
+ {
45637
+ toolName,
45638
+ toolArgsJson: argsJson,
45639
+ orgName: this.orgName,
45640
+ // Passed through unredacted — caller vouches for the contents.
45641
+ resolved: input.resolved
45642
+ },
45643
+ true
45644
+ ),
45645
+ this.decisionTimeoutMs
45646
+ );
45647
+ return this.decide(result);
45648
+ } catch (err) {
45649
+ if (err instanceof SignatureVerificationError) {
45650
+ this.failJudge(errorMessage(err), err);
45110
45651
  return {
45111
45652
  allow: false,
45112
- verdict: "BLOCK",
45113
- reason: result.reason,
45114
- toolCallId: result.toolCallId
45653
+ verdict: "ERROR",
45654
+ reason: `The judge's reply was not trusted (${errorMessage(err)}).`
45115
45655
  };
45116
45656
  }
45117
- if (action === "hold_for_user_confirm") {
45657
+ if (err instanceof JudgeRefusalError || err instanceof AtbashAPIError && isRefusalStatus(err.status)) {
45658
+ return { ...this.failJudge(errorMessage(err), err), allow: false };
45659
+ }
45660
+ return this.failJudge(errorMessage(err), err);
45661
+ }
45662
+ }
45663
+ /**
45664
+ * The verify keys for one call (R4, governor tier-2 review). A per-call key
45665
+ * may only narrow what the client accepts: on a client pinned to judge keys
45666
+ * it must be one of them, never a replacement; on an unpinned client it
45667
+ * adds the check.
45668
+ */
45669
+ effectiveVerifyKeys(perCall) {
45670
+ if (perCall === void 0) return this.verifyKeys;
45671
+ const key3 = perCall.trim().toLowerCase();
45672
+ if (this.verifyKeys.length > 0 && !this.verifyKeys.includes(key3)) {
45673
+ throw new SignatureVerificationError(
45674
+ "a per-call verifyPubKey cannot replace the judge key this client is pinned to"
45675
+ );
45676
+ }
45677
+ return [key3];
45678
+ }
45679
+ /**
45680
+ * Collapse a judge result into a {@link Decision}. The most restrictive
45681
+ * signal wins (security review 2026-09-30, H1): `action_type`, `verdict`
45682
+ * and the canonical `allow` are each able to deny, and only a result where
45683
+ * all three agree may execute. A present `allow` / `decision.allow` that is
45684
+ * not exactly `true` is the judge declining to grant permission, so it
45685
+ * denies even under `failClosed: false` — that option relaxes *errors*, it
45686
+ * never overrides a refusal.
45687
+ */
45688
+ decide(result) {
45689
+ const decided = this.applyMode(result);
45690
+ const inner = {
45691
+ ...decided,
45692
+ ...result.judgmentId ? { judgmentId: result.judgmentId } : {},
45693
+ ...result.record ? { record: result.record } : {}
45694
+ };
45695
+ if (!result.enforcementMode) return inner;
45696
+ return {
45697
+ ...inner,
45698
+ enforced: result.enforced,
45699
+ enforcementMode: result.enforcementMode
45700
+ };
45701
+ }
45702
+ /**
45703
+ * Apply the organisation's enforcement mode to the judge's true verdict.
45704
+ *
45705
+ * Only a mode that arrived signed and bound to this call counts; a missing,
45706
+ * unsigned or unknown mode, or enforceLocally, means enforce. Under
45707
+ * `shadow`, `monitor` or `off` a BLOCK or HOLD runs, reported in
45708
+ * `wouldVerdict`. An ERROR stays an error: it is not a verdict.
45709
+ */
45710
+ applyMode(result) {
45711
+ const mode = result.enforcementMode;
45712
+ const relaxes = this.modeTrusted.has(result) && (mode === "shadow" || mode === "monitor" || mode === "off");
45713
+ if (result.status === "shadow_recorded" && result.verdict === "No verdict") {
45714
+ if (!relaxes || this.enforceLocally) {
45118
45715
  return {
45119
45716
  allow: false,
45120
- verdict: "HOLD",
45121
- reason: result.reason || "held for human confirmation",
45717
+ verdict: "ERROR",
45718
+ reason: "Atbash recorded this action without judging it (the organisation is not enforcing), and this client requires a verdict.",
45122
45719
  toolCallId: result.toolCallId
45123
45720
  };
45124
45721
  }
45125
- if (action === "allow") {
45126
- if (result.verdict === "HOLD") {
45127
- return {
45128
- allow: false,
45129
- verdict: "HOLD",
45130
- reason: result.reason,
45131
- toolCallId: result.toolCallId
45132
- };
45133
- }
45134
- if (result.verdict === "BLOCK") {
45135
- return {
45136
- allow: false,
45137
- verdict: "BLOCK",
45138
- reason: result.reason,
45139
- toolCallId: result.toolCallId
45140
- };
45141
- }
45722
+ this.logger.info?.(`[atbash] recorded in ${mode} mode; not judged yet`, {
45723
+ toolCallId: result.toolCallId
45724
+ });
45725
+ return {
45726
+ allow: true,
45727
+ verdict: "ALLOW",
45728
+ reason: `Recorded in ${mode} mode; the verdict appears in the dashboard.`,
45729
+ toolCallId: result.toolCallId
45730
+ };
45731
+ }
45732
+ const inner = this.decideInner(result);
45733
+ if (!relaxes || this.enforceLocally || inner.allow) return inner;
45734
+ if (inner.verdict !== "BLOCK" && inner.verdict !== "HOLD") return inner;
45735
+ this.logger.warn?.(`[atbash] would ${inner.verdict.toLowerCase()} (${mode} mode): ${inner.reason ?? ""}`, {
45736
+ toolCallId: inner.toolCallId
45737
+ });
45738
+ return {
45739
+ allow: true,
45740
+ verdict: "ALLOW",
45741
+ reason: inner.reason,
45742
+ toolCallId: inner.toolCallId,
45743
+ wouldVerdict: inner.verdict
45744
+ };
45745
+ }
45746
+ decideInner(result) {
45747
+ const toolCallId = result.toolCallId;
45748
+ const deny = (verdict, reason) => ({
45749
+ allow: false,
45750
+ verdict,
45751
+ reason,
45752
+ toolCallId
45753
+ });
45754
+ const notGranted = "the judge response did not grant permission";
45755
+ const held = deny("HOLD", result.reason || "held for human confirmation");
45756
+ const blocked = deny("BLOCK", result.reason || notGranted);
45757
+ if (result.refusal === "BLOCK") return blocked;
45758
+ if (result.verdict === "No verdict") {
45759
+ if (result.actionType === "block") {
45760
+ return blocked;
45761
+ }
45762
+ if (result.actionType === "hold_for_user_confirm") {
45763
+ return held;
45764
+ }
45765
+ if (result.refusal === "HOLD") return held;
45766
+ if (result.status !== "logged") {
45767
+ return this.failJudge(
45768
+ `judge returned no verdict without an audit-tier marker (status: ${result.status || "absent"})`,
45769
+ void 0,
45770
+ toolCallId
45771
+ );
45772
+ }
45773
+ if (this.requireEnforcement) {
45774
+ this.logger.warn?.(
45775
+ "[atbash] judge did not enforce this action (audit tier) and requireEnforcement is on: denied",
45776
+ { toolCallId }
45777
+ );
45142
45778
  return {
45143
- allow: true,
45144
- verdict: "ALLOW",
45145
- reason: result.reason,
45146
- toolCallId: result.toolCallId
45779
+ allow: false,
45780
+ verdict: "ERROR",
45781
+ // The judge's own reason says why it did not check (the plan, a
45782
+ // deactivated agent); a fixed "audit-tier plan" hid which.
45783
+ reason: result.reason ? `Atbash did not check this action, and this client requires a checked decision. The judge said: ${result.reason}` : "Atbash logged this action but did not check it (audit-tier plan), and this client requires a checked decision. Upgrade the plan, or set requireEnforcement: false for log-only mode.",
45784
+ toolCallId
45147
45785
  };
45148
45786
  }
45149
- return this.failJudge(
45150
- "unrecognized action_type from judge",
45151
- void 0,
45152
- result.toolCallId
45153
- );
45154
- } catch (err) {
45155
- return this.failJudge(errorMessage(err), err);
45787
+ if (result.allow !== true) return deny("BLOCK", notGranted);
45788
+ return {
45789
+ allow: true,
45790
+ verdict: "ALLOW",
45791
+ reason: result.reason || "audit tier \u2014 request logged on-chain, no AI enforcement",
45792
+ toolCallId
45793
+ };
45794
+ }
45795
+ const action = result.actionType;
45796
+ if (action === "block") {
45797
+ return deny("BLOCK", result.reason || "Blocked by your organisation's Atbash policy.");
45156
45798
  }
45799
+ if (action === "hold_for_user_confirm") {
45800
+ return held;
45801
+ }
45802
+ if (result.refusal === "HOLD") return held;
45803
+ if (action === "allow") {
45804
+ if (result.verdict === "HOLD") return held;
45805
+ if (result.verdict === "BLOCK") return blocked;
45806
+ if (result.allow !== true) return deny("BLOCK", notGranted);
45807
+ return {
45808
+ allow: true,
45809
+ verdict: "ALLOW",
45810
+ reason: result.reason,
45811
+ toolCallId
45812
+ };
45813
+ }
45814
+ return this.failJudge(
45815
+ "unrecognized action_type from judge",
45816
+ void 0,
45817
+ toolCallId
45818
+ );
45157
45819
  }
45158
45820
  /**
45159
45821
  * One exit for every judge failure.
@@ -45165,18 +45827,30 @@ var Atbash = class _Atbash {
45165
45827
  */
45166
45828
  failJudge(reason, cause, toolCallId) {
45167
45829
  const api2 = cause instanceof AtbashAPIError ? cause : null;
45830
+ const userReason = userFacingReason(reason, api2);
45168
45831
  const status = api2 ? ` status=${api2.status || "no-response"}` : "";
45832
+ const detail = this.debug ? ` detail=${truncate(reason, 500)}` : "";
45169
45833
  const body = this.debug && api2?.body ? ` body=${truncate(api2.body, 500)}` : "";
45170
45834
  this.logger.warn?.(
45171
- `[atbash] judge API failed \u2014${status} reason=${truncate(reason, 300)}${body}`,
45835
+ `[atbash] judge API failed \u2014${status} reason=${truncate(userReason, 300)}${detail}${body}`,
45172
45836
  {
45173
- reason,
45174
- ...api2 ? { status: api2.status, body: api2.body } : {},
45837
+ reason: userReason,
45838
+ ...api2 ? { status: api2.status } : {},
45839
+ ...this.debug && api2 ? { body: api2.body, detail: reason } : {},
45175
45840
  endpoint: this.endpoint,
45176
45841
  ...toolCallId ? { toolCallId } : {}
45177
45842
  }
45178
45843
  );
45179
- return this.fail(reason, toolCallId);
45844
+ return this.fail(userReason, toolCallId);
45845
+ }
45846
+ /**
45847
+ * The canonical permission for a response body under this client's
45848
+ * settings: {@link canonicalAllow}, minus the audit tier when
45849
+ * `requireEnforcement` is on. Never more permissive than `auditToolCall`.
45850
+ */
45851
+ executable(data) {
45852
+ if (!canonicalAllow(data)) return false;
45853
+ return !(this.requireEnforcement && isAuditTierBody(data));
45180
45854
  }
45181
45855
  fail(reason, toolCallId) {
45182
45856
  return { allow: !this.failClosed, verdict: "ERROR", reason, toolCallId };
@@ -45185,33 +45859,63 @@ var Atbash = class _Atbash {
45185
45859
  /**
45186
45860
  * Return the current status of a previously submitted judgment.
45187
45861
  *
45188
- * `chainOpts` names which chain the judgment was signed against. The
45189
- * server's GET /api/v1/judge routes to that chain when the SDK sends
45190
- * a `brid` query param; without it, the server falls back to public.
45191
- * Callers on the private chain must pass a `chainOpts` (or configure
45192
- * the client on the private chain) — otherwise polling a POSTed
45193
- * judgment on the private chain 404s at the server.
45862
+ * `chainOpts` names which chain the judgment was signed against; the SDK
45863
+ * sends it as the `brid` query param the server routes by. Without it the
45864
+ * read uses the same chain `judgeAction` signs for (see `callBrid`): the
45865
+ * client's org chain when it has an `orgName`, else the client default.
45866
+ * A judgment signed with an explicit per-call `chainOpts` (or a per-call
45867
+ * `orgName` on another chain) must be polled with that same `chainOpts`.
45194
45868
  */
45195
45869
  async getJudgmentStatus(judgmentId, agentPubkey, chainOpts) {
45196
45870
  const pk = agentPubkey ?? this.auth.pubkey;
45197
- const brid = this.bridFromChainOpts(chainOpts);
45198
45871
  return this.track("getJudgmentStatus", pk, async () => {
45872
+ const brid = await this.callBrid(chainOpts);
45873
+ const optIn = this.verifyKeys.length > 0 || this.enforceLocally;
45874
+ const optInValue = this.enforceLocally ? "strict" : "1";
45199
45875
  const resp = await this.http.get(
45200
45876
  "/api/v1/judge",
45201
45877
  { tool_call_id: judgmentId, agent_pubkey: pk, brid },
45202
- this.authHeaders(brid)
45878
+ {
45879
+ ...this.authHeaders(brid),
45880
+ ...optIn ? { "X-Atbash-Client-Enforcement": optInValue } : {}
45881
+ }
45203
45882
  );
45204
45883
  await this.raiseIfError(resp);
45205
- const data = await this.json(resp) ?? {};
45206
- return {
45884
+ const bytes = Buffer.from(await resp.arrayBuffer());
45885
+ if (this.verifyKeys.length > 0) {
45886
+ verifyResponseSignature(bytes, resp, this.verifyKeys);
45887
+ }
45888
+ const parsed = tryParseJson(bytes.toString("utf-8"));
45889
+ const data = isRecord2(parsed) ? parsed : {};
45890
+ const rawId = data.tool_call_id;
45891
+ const statedId = wireText(rawId);
45892
+ const sameCall = rawId === void 0 || rawId === null || statedId === judgmentId;
45893
+ let modeTrusted = false;
45894
+ if (optIn) {
45895
+ const echo = data.client_enforcement;
45896
+ if (echo !== void 0 && echo !== optInValue || echo === void 0 && this.enforceLocally) {
45897
+ throw new SignatureVerificationError(
45898
+ "the status does not confirm the enforcement this client asked for"
45899
+ );
45900
+ }
45901
+ modeTrusted = this.verifyKeys.length > 0 && echo === optInValue && statedId === judgmentId;
45902
+ }
45903
+ const status = {
45207
45904
  status: normalizeStatus(data.status),
45208
45905
  verdict: normalizeVerdict(data.verdict),
45209
- reason: String(data.reason ?? ""),
45210
- judgmentId: String(data.judgmentId ?? judgmentId),
45211
- onChain: optBool(data.onChain),
45212
- cached: optBool(data.cached),
45213
- responseTimeMs: optNumber(data.responseTimeMs)
45906
+ allow: sameCall && this.executable(data),
45907
+ reason: wireText(data.reason),
45908
+ judgmentId: statedId || judgmentId,
45909
+ responseTimeMs: optNumber(data.response_time_ms)
45214
45910
  };
45911
+ const mode = wireText(data.enforcement_mode);
45912
+ if (!modeTrusted || this.enforceLocally || !(mode === "shadow" || mode === "monitor" || mode === "off") || status.verdict !== "BLOCK" && status.verdict !== "HOLD") {
45913
+ return status;
45914
+ }
45915
+ this.logger.warn?.(`[atbash] would ${status.verdict.toLowerCase()} (${mode} mode): ${status.reason}`, {
45916
+ toolCallId: judgmentId
45917
+ });
45918
+ return { ...status, verdict: "ALLOW", allow: true, wouldVerdict: status.verdict };
45215
45919
  });
45216
45920
  }
45217
45921
  /* ── risk-engine queries (action-dispatched GET) ───────────────────────── */
@@ -45265,7 +45969,7 @@ var Atbash = class _Atbash {
45265
45969
  { tool_call_id: toolCallId },
45266
45970
  await this.defaultOrgBrid()
45267
45971
  );
45268
- if (!isRecord(raw2)) return null;
45972
+ if (!isRecord2(raw2)) return null;
45269
45973
  return toToolCallFull(raw2);
45270
45974
  });
45271
45975
  }
@@ -45277,7 +45981,7 @@ var Atbash = class _Atbash {
45277
45981
  { org: orgName },
45278
45982
  brid
45279
45983
  );
45280
- if (!isRecord(raw2)) return null;
45984
+ if (!isRecord2(raw2)) return null;
45281
45985
  return {
45282
45986
  orgName: String(raw2.org_name ?? ""),
45283
45987
  tier: String(raw2.tier ?? ""),
@@ -45354,7 +46058,7 @@ var Atbash = class _Atbash {
45354
46058
  );
45355
46059
  await this.raiseIfError(resp);
45356
46060
  const data = await this.json(resp) ?? {};
45357
- if (isRecord(data.data)) return data.data;
46061
+ if (isRecord2(data.data)) return data.data;
45358
46062
  return data;
45359
46063
  });
45360
46064
  }
@@ -45370,7 +46074,7 @@ var Atbash = class _Atbash {
45370
46074
  if (network) params.network = network;
45371
46075
  const brid = network ? this.bridFromChainOpts({ network }) : void 0;
45372
46076
  const raw2 = await this.riskEngineGet("org-subscription", params, brid);
45373
- if (!isRecord(raw2)) return null;
46077
+ if (!isRecord2(raw2)) return null;
45374
46078
  return coerceOrgSubscription(raw2, orgName);
45375
46079
  });
45376
46080
  }
@@ -45394,21 +46098,16 @@ var Atbash = class _Atbash {
45394
46098
  }
45395
46099
  if (resp.status !== 200) throw await this.httpError(resp);
45396
46100
  const data = await this.json(resp);
45397
- if (data?.network === "public" || data?.network === "private") {
45398
- return data.network;
45399
- }
46101
+ if (data?.network === "private") return data.network;
45400
46102
  return null;
45401
46103
  }
45402
46104
  /**
45403
46105
  * Resolve which chain an org's actions should run against. Cached
45404
46106
  * per-client by orgName. Resolution order:
45405
46107
  * 1. `org_networks` map (authoritative).
45406
- * 2. Per-chain subscription fallback — public + private records
45407
- * are fetched in parallel, with `is_private_blockchain` and
45408
- * `assigned_at` reconciling mixed states.
45409
- * A lookup that names exactly one chain wins outright. Where it names
45410
- * neither (a brand-new org) or cannot choose between them, the client's
45411
- * configured default decides.
46108
+ * 2. Subscription fallback — the org's subscription row on the chain.
46109
+ * A lookup that finds the org wins outright. Where it finds nothing (a
46110
+ * brand-new org), the client's configured default decides.
45412
46111
  */
45413
46112
  async resolveChainForOrg(orgName) {
45414
46113
  const name2 = orgName.trim();
@@ -45430,35 +46129,14 @@ var Atbash = class _Atbash {
45430
46129
  const cached = this._chainCache.get(orgName);
45431
46130
  if (cached) return cached;
45432
46131
  if (mapNetwork) {
45433
- const chain = mapNetwork === "private" ? PRIVATE_CHAIN : PUBLIC_CHAIN;
46132
+ const chain = chainForNetwork(mapNetwork);
45434
46133
  this._chainCache.set(orgName, chain);
45435
46134
  return chain;
45436
46135
  }
45437
- const [pubRes, privRes] = await Promise.allSettled([
45438
- this.getOrgSubscription(orgName, "public"),
45439
- this.getOrgSubscription(orgName, "private")
45440
- ]);
45441
- const pubSub = pubRes.status === "fulfilled" ? pubRes.value : null;
45442
- const privSub = privRes.status === "fulfilled" ? privRes.value : null;
45443
- const failure = pubRes.status === "rejected" ? pubRes.reason : privRes.status === "rejected" ? privRes.reason : null;
45444
- if (pubSub?.is_private_blockchain) {
45445
- this._chainCache.set(orgName, PRIVATE_CHAIN);
45446
- return PRIVATE_CHAIN;
45447
- }
45448
- if (pubSub && privSub) {
45449
- const chain = privSub.assigned_at === pubSub.assigned_at ? this._defaultChain : privSub.assigned_at > pubSub.assigned_at ? PRIVATE_CHAIN : PUBLIC_CHAIN;
45450
- this._chainCache.set(orgName, chain);
45451
- return chain;
45452
- }
45453
- if (pubSub) {
45454
- this._chainCache.set(orgName, PUBLIC_CHAIN);
45455
- return PUBLIC_CHAIN;
45456
- }
45457
- if (privSub?.is_private_blockchain) {
45458
- this._chainCache.set(orgName, PRIVATE_CHAIN);
45459
- return PRIVATE_CHAIN;
45460
- }
45461
- if (failure) {
46136
+ let privSub;
46137
+ try {
46138
+ privSub = await this.getOrgSubscription(orgName, "private");
46139
+ } catch (failure) {
45462
46140
  const detail = failure instanceof Error ? failure.message : String(failure);
45463
46141
  throw new AtbashAPIError(
45464
46142
  failure instanceof AtbashAPIError ? failure.status : 0,
@@ -45467,6 +46145,10 @@ var Atbash = class _Atbash {
45467
46145
  this.endpoint
45468
46146
  );
45469
46147
  }
46148
+ if (privSub) {
46149
+ this._chainCache.set(orgName, PRIVATE_CHAIN);
46150
+ return PRIVATE_CHAIN;
46151
+ }
45470
46152
  this._chainCache.set(orgName, this._defaultChain);
45471
46153
  return this._defaultChain;
45472
46154
  }
@@ -45491,10 +46173,28 @@ var Atbash = class _Atbash {
45491
46173
  recordCall(name2, void 0, agentPubkey);
45492
46174
  try {
45493
46175
  const result = await fn();
45494
- recordDuration(name2, performance.now() - start, "success");
46176
+ const durationMs = performance.now() - start;
46177
+ recordDuration(name2, durationMs, "success");
46178
+ recordEvent({
46179
+ functionName: name2,
46180
+ durationMs,
46181
+ status: "success",
46182
+ agentPubkey,
46183
+ chain: this.blockchainRid
46184
+ });
45495
46185
  return result;
45496
46186
  } catch (err) {
45497
- recordDuration(name2, performance.now() - start, "error");
46187
+ const durationMs = performance.now() - start;
46188
+ recordDuration(name2, durationMs, "error");
46189
+ recordEvent({
46190
+ functionName: name2,
46191
+ durationMs,
46192
+ status: "error",
46193
+ agentPubkey,
46194
+ chain: this.blockchainRid,
46195
+ errorClass: err instanceof Error ? err.constructor.name : typeof err,
46196
+ ...errorDetail(err)
46197
+ });
45498
46198
  throw err;
45499
46199
  }
45500
46200
  }
@@ -45505,10 +46205,21 @@ var Atbash = class _Atbash {
45505
46205
  */
45506
46206
  bridFromChainOpts(chainOpts) {
45507
46207
  if (chainOpts?.blockchainRid) return chainOpts.blockchainRid;
45508
- if (chainOpts?.network === "private") return PRIVATE_CHAIN.blockchainRid;
45509
- if (chainOpts?.network === "public") return PUBLIC_CHAIN.blockchainRid;
46208
+ if (chainOpts?.network) return chainForNetwork(chainOpts.network).blockchainRid;
45510
46209
  return this.blockchainRid;
45511
46210
  }
46211
+ /**
46212
+ * The chain one call's transactions are signed for: the per-call override
46213
+ * when given, otherwise the client's org, otherwise the client default.
46214
+ * log_tool_call, judge_action and the judgment-status read all use this, so
46215
+ * a request never pairs transactions signed for two different chains.
46216
+ */
46217
+ async callBrid(chainOpts) {
46218
+ if (chainOpts?.blockchainRid || chainOpts?.network) {
46219
+ return this.bridFromChainOpts(chainOpts);
46220
+ }
46221
+ return await this.defaultOrgBrid() ?? this.blockchainRid;
46222
+ }
45512
46223
  /**
45513
46224
  * Resolve the dashboard chain used by agent metadata/policy reads.
45514
46225
  * Explicit per-call network overrides win; otherwise use the supplied org
@@ -45532,25 +46243,10 @@ var Atbash = class _Atbash {
45532
46243
  * trips the server's replay window.
45533
46244
  */
45534
46245
  getAuthBearer(brid) {
45535
- const chainBrid = brid ?? this.blockchainRid;
45536
- const now = Date.now();
45537
- const cached = this._authBearers.get(chainBrid);
45538
- if (cached && now - cached.issuedAt < 4 * 60 * 1e3) return cached.hex;
45539
- const nonce = `auth-${now.toString(36)}-${randomHex(4)}`;
45540
- const hex = native.signLogToolCall(
45541
- nonce,
45542
- `auth:${now}`,
45543
- "",
45544
- "auth-bearer",
45545
- "",
45546
- this.auth.privkey,
45547
- chainBrid
45548
- );
45549
- this._authBearers.set(chainBrid, { hex, issuedAt: now });
45550
- return hex;
46246
+ return agentAuthBearer(this.auth, brid ?? this.blockchainRid);
45551
46247
  }
45552
46248
  authHeaders(brid) {
45553
- return { Authorization: `Bearer ${this.getAuthBearer(brid)}` };
46249
+ return agentAuthHeaders(this.auth, brid ?? this.blockchainRid);
45554
46250
  }
45555
46251
  async riskEngineGet(action, params, brid) {
45556
46252
  let resp;
@@ -45569,14 +46265,14 @@ var Atbash = class _Atbash {
45569
46265
  async riskEnginePost(body, network, brid) {
45570
46266
  let resp;
45571
46267
  try {
45572
- const path4 = network ? `/api/risk-engine?network=${encodeURIComponent(network)}` : "/api/risk-engine";
45573
- resp = await this.http.post(path4, body, this.authHeaders(brid));
46268
+ const path3 = network ? `/api/risk-engine?network=${encodeURIComponent(network)}` : "/api/risk-engine";
46269
+ resp = await this.http.post(path3, body, this.authHeaders(brid));
45574
46270
  } catch (err) {
45575
46271
  throw this.transportError(err);
45576
46272
  }
45577
46273
  if (resp.status !== 200) throw await this.httpError(resp);
45578
46274
  const data = await this.json(resp);
45579
- return isRecord(data) ? data : {};
46275
+ return isRecord2(data) ? data : {};
45580
46276
  }
45581
46277
  async riskEngineRecords(action, params, brid) {
45582
46278
  const raw2 = await this.riskEngineGet(action, params, brid);
@@ -45630,7 +46326,8 @@ var Atbash = class _Atbash {
45630
46326
  resp.status,
45631
46327
  await safeText(resp),
45632
46328
  resp.statusText,
45633
- this.endpoint
46329
+ this.endpoint,
46330
+ requestPath(resp.url)
45634
46331
  );
45635
46332
  }
45636
46333
  /**
@@ -45643,14 +46340,11 @@ var Atbash = class _Atbash {
45643
46340
  transportError(err) {
45644
46341
  if (err instanceof HttpTransportError) {
45645
46342
  if (this.debug) {
45646
- this.logger.warn?.(
45647
- `[atbash] transport failed \u2014 kind=${err.kind}`,
45648
- {
45649
- kind: err.kind,
45650
- cause: err.cause instanceof Error ? err.cause.message : String(err.cause ?? ""),
45651
- endpoint: this.endpoint
45652
- }
45653
- );
46343
+ this.logger.warn?.(`[atbash] transport failed \u2014 kind=${err.kind}`, {
46344
+ kind: err.kind,
46345
+ cause: err.cause instanceof Error ? err.cause.message : String(err.cause ?? ""),
46346
+ endpoint: this.endpoint
46347
+ });
45654
46348
  }
45655
46349
  return new AtbashAPIError(0, err.message, "", this.endpoint);
45656
46350
  }
@@ -45682,6 +46376,66 @@ var Atbash = class _Atbash {
45682
46376
  return native.containsEvasionCharacters(text);
45683
46377
  }
45684
46378
  };
46379
+ function userFacingReason(reason, api2) {
46380
+ if (api2 && api2.status > 0) {
46381
+ const where = ` (HTTP ${api2.status}${api2.path ? ` from ${api2.path}` : ""})`;
46382
+ const b = api2.body.toLowerCase();
46383
+ if (b.includes("agent not registered")) {
46384
+ return `Agent not registered with Atbash: onboard it in the Atbash dashboard${where}.`;
46385
+ }
46386
+ if (b.includes("jailed")) {
46387
+ return `This agent is jailed; unjail it in the Atbash dashboard${where}.`;
46388
+ }
46389
+ if (b.includes("agent has no policy") || b.includes("no policy configured")) {
46390
+ return `This agent has no policy; attach one in the Atbash dashboard${where}.`;
46391
+ }
46392
+ if (b.includes("audit tier") || b.includes("verdict disabled") || b.includes("verdict not supported")) {
46393
+ return `The organisation's plan does not include checked decisions${where}.`;
46394
+ }
46395
+ return `The Atbash judge answered with an error${where}, so the action was not approved.`;
46396
+ }
46397
+ const text = api2 ? api2.body || reason : reason;
46398
+ return truncate(text.replace(/https?:\/\/[^\s)]+/g, "the judge"), 300);
46399
+ }
46400
+ var DEFAULT_DECISION_TIMEOUT_MS = 6e4;
46401
+ async function withDeadline(p, ms) {
46402
+ let timer;
46403
+ const deadline = new Promise((_, reject) => {
46404
+ timer = setTimeout(
46405
+ () => reject(
46406
+ new Error(
46407
+ `The judge did not give a decision within ${Math.round(ms / 1e3)} s, so the action was not approved. Check the network, or raise decisionTimeoutMs.`
46408
+ )
46409
+ ),
46410
+ ms
46411
+ );
46412
+ });
46413
+ p.catch(() => void 0);
46414
+ try {
46415
+ return await Promise.race([p, deadline]);
46416
+ } finally {
46417
+ clearTimeout(timer);
46418
+ }
46419
+ }
46420
+ function verifyResponseSignature(bodyBytes, resp, verifyKeys) {
46421
+ const sig = resp.headers.get("X-Atbash-Signature");
46422
+ if (!sig) {
46423
+ throw new SignatureVerificationError("missing X-Atbash-Signature header");
46424
+ }
46425
+ let ok = false;
46426
+ try {
46427
+ ok = verifyKeys.some((key3) => native.verifySignature(bodyBytes, sig, key3));
46428
+ } catch (err) {
46429
+ throw new SignatureVerificationError(
46430
+ `signature verification threw: ${errorMessage(err)}`
46431
+ );
46432
+ }
46433
+ if (!ok) {
46434
+ throw new SignatureVerificationError(
46435
+ "signature does not verify against configured verifyPubKey"
46436
+ );
46437
+ }
46438
+ }
45685
46439
  function baseToolCall(raw2) {
45686
46440
  return {
45687
46441
  toolCallId: String(raw2.tool_call_id ?? ""),
@@ -45748,22 +46502,20 @@ function coerceOrgSubscription(raw2, orgName) {
45748
46502
  is_active: Boolean(raw2.is_active)
45749
46503
  };
45750
46504
  }
45751
- function isRecord(v) {
46505
+ function isRecord2(v) {
45752
46506
  return typeof v === "object" && v !== null && !Array.isArray(v);
45753
46507
  }
45754
46508
  function optString(v) {
45755
46509
  if (v === null || v === void 0) return void 0;
46510
+ if (typeof v === "object" || typeof v === "function") return void 0;
45756
46511
  return typeof v === "string" ? v : String(v);
45757
46512
  }
45758
46513
  function optNumber(v) {
45759
46514
  if (v === null || v === void 0) return void 0;
46515
+ if (typeof v === "object" || typeof v === "function") return void 0;
45760
46516
  const n = Number(v);
45761
46517
  return Number.isFinite(n) ? n : void 0;
45762
46518
  }
45763
- function optBool(v) {
45764
- if (v === null || v === void 0) return void 0;
45765
- return Boolean(v);
45766
- }
45767
46519
  function tryParseJson(text) {
45768
46520
  try {
45769
46521
  return JSON.parse(text);
@@ -45771,9 +46523,13 @@ function tryParseJson(text) {
45771
46523
  return void 0;
45772
46524
  }
45773
46525
  }
45774
- function parseJson(bytes) {
45775
- const parsed = tryParseJson(bytes.toString("utf-8"));
45776
- return parsed === void 0 ? {} : parsed;
46526
+ function requestPath(url) {
46527
+ if (!url) return void 0;
46528
+ try {
46529
+ return new URL(url).pathname || void 0;
46530
+ } catch {
46531
+ return void 0;
46532
+ }
45777
46533
  }
45778
46534
  async function safeText(resp) {
45779
46535
  try {
@@ -45804,32 +46560,25 @@ function truncate(text, limit = MAX_ACTION_LEN) {
45804
46560
  return text.slice(0, limit) + "\u2026";
45805
46561
  }
45806
46562
 
45807
- // src-ts/key-path.ts
45808
- init_define_ATBASH_CHROMIA_NODE_URLS();
46563
+ // src-ts/browser/key-path.ts
46564
+ init_define_ATBASH_DEV_JUDGE_PINS();
45809
46565
  init_define_ATBASH_PRIVATE_NODE_URLS();
45810
- import { homedir } from "os";
45811
- import { join as join2 } from "path";
45812
- var KEY_DIR_REL = ".config/atbash";
46566
+ init_define_ATBASH_PROD_JUDGE_PINS();
45813
46567
  var KEY_FILENAMES = ["guard-client-key", "atbash-client-key"];
45814
- function home() {
45815
- return process.env.HOME || homedir() || "";
45816
- }
45817
- function expandHome(p) {
45818
- if (!p.startsWith("~/")) return p;
45819
- return join2(home(), p.slice(2));
45820
- }
46568
+ var unavailable = (name2) => {
46569
+ throw new Error(`${name2} is not available in the browser bundle`);
46570
+ };
45821
46571
  function keyPathCandidates() {
45822
- return KEY_FILENAMES.map((name2) => join2(home(), KEY_DIR_REL, name2));
46572
+ return unavailable("keyPathCandidates");
45823
46573
  }
45824
- function chooseKeyPath(input, exists) {
45825
- if (input) return expandHome(input);
45826
- const candidates = keyPathCandidates();
45827
- return candidates.find(exists) ?? candidates[0];
46574
+ function chooseKeyPath(_input, _exists) {
46575
+ return unavailable("chooseKeyPath");
45828
46576
  }
45829
46577
 
45830
46578
  // src-ts/redact.ts
45831
- init_define_ATBASH_CHROMIA_NODE_URLS();
46579
+ init_define_ATBASH_DEV_JUDGE_PINS();
45832
46580
  init_define_ATBASH_PRIVATE_NODE_URLS();
46581
+ init_define_ATBASH_PROD_JUDGE_PINS();
45833
46582
  function redactJsonStrings(value) {
45834
46583
  if (typeof value === "string") {
45835
46584
  return native.redactSecrets(value).redacted;
@@ -45848,8 +46597,9 @@ function redactJsonStrings(value) {
45848
46597
  }
45849
46598
 
45850
46599
  // src-ts/signature.ts
45851
- init_define_ATBASH_CHROMIA_NODE_URLS();
46600
+ init_define_ATBASH_DEV_JUDGE_PINS();
45852
46601
  init_define_ATBASH_PRIVATE_NODE_URLS();
46602
+ init_define_ATBASH_PROD_JUDGE_PINS();
45853
46603
  function verifyJudgeResponseSignature(bodyBytes, signatureHex, pubKeyHex) {
45854
46604
  if (!signatureHex) {
45855
46605
  return { ok: false, reason: "missing X-Atbash-Signature header" };
@@ -45872,8 +46622,9 @@ function verifyJudgeResponseSignature(bodyBytes, signatureHex, pubKeyHex) {
45872
46622
  }
45873
46623
 
45874
46624
  // src-ts/memory/boot-sync-message.ts
45875
- init_define_ATBASH_CHROMIA_NODE_URLS();
46625
+ init_define_ATBASH_DEV_JUDGE_PINS();
45876
46626
  init_define_ATBASH_PRIVATE_NODE_URLS();
46627
+ init_define_ATBASH_PROD_JUDGE_PINS();
45877
46628
  var BOOT_SYNC_HINT = "check the chain endpoint and orgName if the cause above does not explain it";
45878
46629
  function bootSyncFailureLine(cause) {
45879
46630
  const reason = cause instanceof Error ? cause.message : String(cause);
@@ -45885,12 +46636,14 @@ function bootSyncFailureLine(cause) {
45885
46636
  }
45886
46637
 
45887
46638
  // src-ts/memory/index.ts
45888
- init_define_ATBASH_CHROMIA_NODE_URLS();
46639
+ init_define_ATBASH_DEV_JUDGE_PINS();
45889
46640
  init_define_ATBASH_PRIVATE_NODE_URLS();
46641
+ init_define_ATBASH_PROD_JUDGE_PINS();
45890
46642
 
45891
46643
  // src-ts/browser/memory-crypto.ts
45892
- init_define_ATBASH_CHROMIA_NODE_URLS();
46644
+ init_define_ATBASH_DEV_JUDGE_PINS();
45893
46645
  init_define_ATBASH_PRIVATE_NODE_URLS();
46646
+ init_define_ATBASH_PROD_JUDGE_PINS();
45894
46647
  var { Buffer: Buffer4 } = index;
45895
46648
  var HKDF_INFO = new TextEncoder().encode("atbash:memory-encryption");
45896
46649
  var KEY_LEN = 32;
@@ -45965,8 +46718,9 @@ async function decryptMemoryContent2(ciphertext, nonce, key3) {
45965
46718
  }
45966
46719
 
45967
46720
  // src-ts/browser/memory-scan.ts
45968
- init_define_ATBASH_CHROMIA_NODE_URLS();
46721
+ init_define_ATBASH_DEV_JUDGE_PINS();
45969
46722
  init_define_ATBASH_PRIVATE_NODE_URLS();
46723
+ init_define_ATBASH_PROD_JUDGE_PINS();
45970
46724
  var STUB_MSG2 = "not available in @atbash/sdk browser bundle \u2014 scan memory server-side";
45971
46725
  async function scanMemory(_entry, _auth, _opts) {
45972
46726
  throw new Error(`scanMemory ${STUB_MSG2}`);
@@ -45976,8 +46730,9 @@ async function scanMemoryBatch(_entries, _auth, _opts) {
45976
46730
  }
45977
46731
 
45978
46732
  // src-ts/browser/memory-chain.ts
45979
- init_define_ATBASH_CHROMIA_NODE_URLS();
46733
+ init_define_ATBASH_DEV_JUDGE_PINS();
45980
46734
  init_define_ATBASH_PRIVATE_NODE_URLS();
46735
+ init_define_ATBASH_PROD_JUDGE_PINS();
45981
46736
  var STUB_MSG3 = "not available in @atbash/sdk browser bundle \u2014 commit/rollback memory server-side";
45982
46737
  async function commitMemoryVersion(_plaintext, _auth, _opts) {
45983
46738
  throw new Error(`commitMemoryVersion ${STUB_MSG3}`);
@@ -45991,7 +46746,7 @@ async function getRecentAgentMemory(_auth, _chainOpts) {
45991
46746
  async function getActiveAgentMemory(_auth, _chainOpts) {
45992
46747
  throw new Error(`getActiveAgentMemory ${STUB_MSG3}`);
45993
46748
  }
45994
- async function getMemoryHistory(_auth, _chainOpts) {
46749
+ async function getMemoryHistory(_auth, _chainOpts, _filePath, _page) {
45995
46750
  throw new Error(`getMemoryHistory ${STUB_MSG3}`);
45996
46751
  }
45997
46752
  async function getMemoryById(_id, _auth, _chainOpts) {
@@ -46005,8 +46760,9 @@ async function rollbackMemory(_toId, _reason, _auth, _opts) {
46005
46760
  }
46006
46761
 
46007
46762
  // src-ts/browser/memory-classifier.ts
46008
- init_define_ATBASH_CHROMIA_NODE_URLS();
46763
+ init_define_ATBASH_DEV_JUDGE_PINS();
46009
46764
  init_define_ATBASH_PRIVATE_NODE_URLS();
46765
+ init_define_ATBASH_PROD_JUDGE_PINS();
46010
46766
  var STUB_MSG4 = "not available in @atbash/sdk browser bundle \u2014 classify memory writes server-side";
46011
46767
  var DEFAULT_MEMORY_WRITE_TOOL_NAMES = [
46012
46768
  "write",
@@ -46028,117 +46784,30 @@ function classifyMemoryWrite(_event, _ctx, _opts = {}) {
46028
46784
  throw new Error(`classifyMemoryWrite ${STUB_MSG4}`);
46029
46785
  }
46030
46786
 
46031
- // src-ts/memory/guard.ts
46032
- init_define_ATBASH_CHROMIA_NODE_URLS();
46787
+ // src-ts/browser/memory-guard.ts
46788
+ init_define_ATBASH_DEV_JUDGE_PINS();
46033
46789
  init_define_ATBASH_PRIVATE_NODE_URLS();
46034
- import path3 from "path";
46035
- function emitDebugProbe(event, ctx, memEntry, logger2) {
46036
- if (!logger2?.info) return;
46037
- const ev = event ?? {};
46038
- const c = ctx ?? {};
46039
- const argsCandidate = ev.params ?? c.params ?? ev.args ?? c.args ?? ev.arguments ?? c.arguments;
46040
- const argsObj = argsCandidate && typeof argsCandidate === "object" ? argsCandidate : {};
46041
- const argsKeys = Object.keys(argsObj).slice(0, 20);
46042
- const pickedPath = typeof argsObj.file_path === "string" && argsObj.file_path || typeof argsObj.path === "string" && argsObj.path || typeof argsObj.filename === "string" && argsObj.filename || null;
46043
- const editsArr = Array.isArray(argsObj.edits) ? argsObj.edits : null;
46044
- const firstEditKeys = editsArr && editsArr[0] && typeof editsArr[0] === "object" ? Object.keys(editsArr[0]).slice(0, 10) : null;
46045
- const tool = ev.toolName ?? c.tool?.name ?? c.toolName ?? c.name ?? "(none)";
46046
- logger2.info("[atbash][probe] before_tool_call", {
46047
- toolName: tool,
46048
- eventKeys: Object.keys(ev).slice(0, 20),
46049
- ctxKeys: Object.keys(c).slice(0, 20),
46050
- argsKeys,
46051
- pickedPath,
46052
- firstEditKeys,
46053
- editsCount: editsArr?.length,
46054
- memoryWrite: !!memEntry,
46055
- memoryPath: memEntry?.key
46056
- });
46790
+ init_define_ATBASH_PROD_JUDGE_PINS();
46791
+ var STUB_MSG5 = "not available in @atbash/sdk browser bundle \u2014 guard memory writes agent-side";
46792
+ async function guardMemoryWrite(_input) {
46793
+ throw new Error(`guardMemoryWrite ${STUB_MSG5}`);
46057
46794
  }
46058
- async function guardMemoryWrite(input) {
46059
- const {
46060
- event,
46061
- ctx,
46062
- auth,
46063
- endpoint,
46064
- verifyPubKey,
46065
- orgName,
46066
- threshold,
46067
- patterns,
46068
- toolNames,
46069
- enforce = true,
46070
- debug: debug2 = false,
46071
- logger: logger2
46072
- } = input;
46073
- const memEntry = classifyMemoryWrite(event, ctx, { patterns, toolNames });
46074
- if (debug2) emitDebugProbe(event, ctx, memEntry, logger2);
46075
- if (!memEntry) return { handled: false };
46076
- let scanResult;
46077
- try {
46078
- scanResult = await scanMemory(memEntry, auth, {
46079
- endpoint,
46080
- verifyPubKey,
46081
- orgName,
46082
- threshold
46083
- });
46084
- } catch (err) {
46085
- const reason = err instanceof Error ? err.message : String(err);
46086
- logger2?.warn?.("[atbash] memory scan failed", {
46087
- path: memEntry.key,
46088
- reason
46089
- });
46090
- return {
46091
- handled: true,
46092
- decision: enforce ? { allow: false, block: true, reason } : { allow: true }
46093
- };
46094
- }
46095
- if (scanResult.verdict === "red") {
46096
- logger2?.warn?.("[atbash] memory BLOCK", {
46097
- path: memEntry.key,
46098
- reason: scanResult.reason
46099
- });
46100
- return {
46101
- handled: true,
46102
- decision: enforce ? { allow: false, block: true, reason: scanResult.reason } : { allow: true },
46103
- scanResult,
46104
- committed: false
46105
- };
46106
- }
46107
- const filePath = path3.basename(memEntry.key);
46108
- commitMemoryVersion(memEntry.value, auth, {
46109
- score: scanResult.score,
46110
- filePath,
46111
- orgName,
46112
- endpoint,
46113
- verifyPubKey
46114
- }).catch((err) => {
46115
- const reason = err instanceof Error ? err.message : String(err);
46116
- logger2?.warn?.("[atbash] memory commit to chain failed", {
46117
- path: memEntry.key,
46118
- filePath,
46119
- reason
46120
- });
46121
- });
46122
- logger2?.info?.(
46123
- scanResult.verdict === "yellow" ? "[atbash] memory HOLD" : "[atbash] memory ALLOW",
46124
- {
46125
- path: memEntry.key,
46126
- filePath,
46127
- score: scanResult.score,
46128
- reason: scanResult.reason
46129
- }
46130
- );
46131
- return {
46132
- handled: true,
46133
- decision: { allow: true },
46134
- scanResult,
46135
- committed: true
46136
- };
46795
+
46796
+ // src-ts/browser/memory-slot.ts
46797
+ init_define_ATBASH_DEV_JUDGE_PINS();
46798
+ init_define_ATBASH_PRIVATE_NODE_URLS();
46799
+ init_define_ATBASH_PROD_JUDGE_PINS();
46800
+ var unavailable2 = (name2) => {
46801
+ throw new Error(`${name2} is not available in the browser bundle`);
46802
+ };
46803
+ function memorySlotOf(_target, _home, _root2, _extraHomes, _p) {
46804
+ return unavailable2("memorySlotOf");
46137
46805
  }
46138
46806
 
46139
46807
  // src-ts/memory/sync.ts
46140
- init_define_ATBASH_CHROMIA_NODE_URLS();
46808
+ init_define_ATBASH_DEV_JUDGE_PINS();
46141
46809
  init_define_ATBASH_PRIVATE_NODE_URLS();
46810
+ init_define_ATBASH_PROD_JUDGE_PINS();
46142
46811
  var MemoryIntegrityError = class extends Error {
46143
46812
  constructor(id, reason) {
46144
46813
  super(`memory integrity check failed on id ${id}: ${reason}`);
@@ -46155,7 +46824,7 @@ async function syncLocalMemory(auth, pointer, opts = {}) {
46155
46824
  if (withinTtl) {
46156
46825
  return { drifted: false, checked: false, pointer };
46157
46826
  }
46158
- const currentId = await getActiveMemoryId(auth, opts.chainOpts);
46827
+ const currentId = await getActiveMemoryId(auth, opts.chainOpts, opts.filePath);
46159
46828
  const nextPointer = { activeId: currentId, checkedAt: now };
46160
46829
  if (currentId === pointer.activeId) {
46161
46830
  return { drifted: false, checked: true, pointer: nextPointer };
@@ -46171,9 +46840,10 @@ async function syncLocalMemory(auth, pointer, opts = {}) {
46171
46840
  }
46172
46841
 
46173
46842
  // src-ts/browser/memory-pointer-store.ts
46174
- init_define_ATBASH_CHROMIA_NODE_URLS();
46843
+ init_define_ATBASH_DEV_JUDGE_PINS();
46175
46844
  init_define_ATBASH_PRIVATE_NODE_URLS();
46176
- var unavailable = (name2) => {
46845
+ init_define_ATBASH_PROD_JUDGE_PINS();
46846
+ var unavailable3 = (name2) => {
46177
46847
  throw new Error(`${name2} is not available in the browser bundle`);
46178
46848
  };
46179
46849
  var PointerStore = class {
@@ -46187,38 +46857,41 @@ var PointerStore = class {
46187
46857
  }
46188
46858
  };
46189
46859
  function defaultPointerPath(_workspaceDir) {
46190
- return unavailable("defaultPointerPath");
46860
+ return unavailable3("defaultPointerPath");
46191
46861
  }
46192
46862
 
46193
46863
  // src-ts/browser/memory-file-logger.ts
46194
- init_define_ATBASH_CHROMIA_NODE_URLS();
46864
+ init_define_ATBASH_DEV_JUDGE_PINS();
46195
46865
  init_define_ATBASH_PRIVATE_NODE_URLS();
46196
- var unavailable2 = (name2) => {
46866
+ init_define_ATBASH_PROD_JUDGE_PINS();
46867
+ var unavailable4 = (name2) => {
46197
46868
  throw new Error(`${name2} is not available in the browser bundle`);
46198
46869
  };
46199
46870
  function createFileLogger(_logFilePath, _hostLogger) {
46200
- return unavailable2("createFileLogger");
46871
+ return unavailable4("createFileLogger");
46201
46872
  }
46202
46873
  function defaultPluginLogPath(_workspaceDir) {
46203
- return unavailable2("defaultPluginLogPath");
46874
+ return unavailable4("defaultPluginLogPath");
46204
46875
  }
46205
46876
 
46206
46877
  // src-ts/browser/memory-read-classifier.ts
46207
- init_define_ATBASH_CHROMIA_NODE_URLS();
46878
+ init_define_ATBASH_DEV_JUDGE_PINS();
46208
46879
  init_define_ATBASH_PRIVATE_NODE_URLS();
46209
- var STUB_MSG5 = "not available in @atbash/sdk browser bundle \u2014 classify memory reads server-side";
46880
+ init_define_ATBASH_PROD_JUDGE_PINS();
46881
+ var STUB_MSG6 = "not available in @atbash/sdk browser bundle \u2014 classify memory reads server-side";
46210
46882
  var DEFAULT_MEMORY_READ_TOOL_NAMES = [
46211
46883
  "memory_search",
46212
46884
  "memory_get"
46213
46885
  ];
46214
46886
  function classifyMemoryRead(_event, _ctx, _opts = {}) {
46215
- throw new Error(`classifyMemoryRead ${STUB_MSG5}`);
46887
+ throw new Error(`classifyMemoryRead ${STUB_MSG6}`);
46216
46888
  }
46217
46889
 
46218
46890
  // src-ts/browser/memory-guard-manager.ts
46219
- init_define_ATBASH_CHROMIA_NODE_URLS();
46891
+ init_define_ATBASH_DEV_JUDGE_PINS();
46220
46892
  init_define_ATBASH_PRIVATE_NODE_URLS();
46221
- var unavailable3 = (name2) => {
46893
+ init_define_ATBASH_PROD_JUDGE_PINS();
46894
+ var unavailable5 = (name2) => {
46222
46895
  throw new Error(`${name2} is not available in the browser bundle`);
46223
46896
  };
46224
46897
  var MemoryGuardManager = class {
@@ -46238,7 +46911,7 @@ var MemoryGuardManager = class {
46238
46911
  }
46239
46912
  };
46240
46913
  function createMemoryGuardManager(_opts) {
46241
- return unavailable3("createMemoryGuardManager");
46914
+ return unavailable5("createMemoryGuardManager");
46242
46915
  }
46243
46916
 
46244
46917
  // src-ts/index.ts
@@ -46300,8 +46973,6 @@ export {
46300
46973
  Atbash,
46301
46974
  AtbashAPIError,
46302
46975
  BOOT_SYNC_HINT,
46303
- DEFAULT_BLOCKCHAIN_RID,
46304
- DEFAULT_CHROMIA_NODE_URLS,
46305
46976
  DEFAULT_ENDPOINT,
46306
46977
  DEFAULT_MEMORY_PATH_PATTERNS,
46307
46978
  DEFAULT_MEMORY_READ_TOOL_NAMES,
@@ -46309,15 +46980,16 @@ export {
46309
46980
  EciesDomain,
46310
46981
  HttpClient,
46311
46982
  HttpTransportError,
46983
+ JudgeRefusalError,
46312
46984
  KEY_FILENAMES,
46313
46985
  MemoryGuardManager,
46314
46986
  MemoryIntegrityError,
46315
46987
  PRIVATE_CHAIN,
46316
- PUBLIC_CHAIN,
46317
46988
  PointerStore,
46318
46989
  SignatureVerificationError,
46319
46990
  bootSyncFailureLine,
46320
46991
  buildAllowedJudgeHosts,
46992
+ canonicalAllow,
46321
46993
  chainForNetwork,
46322
46994
  chooseKeyPath,
46323
46995
  claimHashHex,
@@ -46325,6 +46997,8 @@ export {
46325
46997
  classifyMemoryWrite,
46326
46998
  columnAad,
46327
46999
  commitMemoryVersion,
47000
+ configureEvents,
47001
+ configureJailHold,
46328
47002
  containsEvasionCharacters2 as containsEvasionCharacters,
46329
47003
  containsSecret2 as containsSecret,
46330
47004
  createFileLogger,
@@ -46340,6 +47014,7 @@ export {
46340
47014
  encryptForOrg,
46341
47015
  encryptMemoryContent2 as encryptMemoryContent,
46342
47016
  encryptedLength,
47017
+ eventsAreOn,
46343
47018
  flushTelemetry,
46344
47019
  generateKeypair2 as generateKeypair,
46345
47020
  getActiveAgentMemory,
@@ -46352,13 +47027,17 @@ export {
46352
47027
  getRollbackHistory,
46353
47028
  guardMemoryWrite,
46354
47029
  isEnvelope,
47030
+ isJailHeld,
46355
47031
  isValidPrivateKey2 as isValidPrivateKey,
47032
+ judgeVerifyKeys,
46356
47033
  keyFingerprintOf,
46357
47034
  keyPathCandidates,
46358
47035
  loadAgent2 as loadAgent,
46359
47036
  loadAgentFromFile,
46360
47037
  loadUserConfig,
47038
+ memorySlotOf,
46361
47039
  normalizeActionForHash,
47040
+ normalizeActionType,
46362
47041
  normalizeForMatching2 as normalizeForMatching,
46363
47042
  normalizeStatus,
46364
47043
  normalizeVerdict,
@@ -46367,14 +47046,17 @@ export {
46367
47046
  pubkeyToHex,
46368
47047
  recordCall,
46369
47048
  recordDuration,
47049
+ recordEvent,
46370
47050
  redactJsonStrings,
46371
47051
  redactSecrets2 as redactSecrets,
47052
+ releaseJailHolds,
46372
47053
  resolve,
46373
47054
  resolveKeyPath,
46374
47055
  rollbackMemory,
46375
47056
  saveUserConfig,
46376
47057
  scanMemory,
46377
47058
  scanMemoryBatch,
47059
+ setLoopbackJudgePinsForTests,
46378
47060
  setupTelemetry,
46379
47061
  shutdownTelemetry,
46380
47062
  signEncryptedToolCall,
@@ -46407,4 +47089,3 @@ postchain-client/built/esm/index.js:
46407
47089
  @noble/ciphers/utils.js:
46408
47090
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
46409
47091
  */
46410
- //# sourceMappingURL=browser.mjs.map