@vultisig/cli 4.5.0 → 4.6.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/index.js CHANGED
@@ -1234,11 +1234,70 @@ var init_base = __esm({
1234
1234
  }
1235
1235
  });
1236
1236
 
1237
+ // ../../node_modules/viem/_esm/errors/abi.js
1238
+ var AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, BytesSizeMismatchError, InvalidAbiEncodingTypeError, InvalidArrayError;
1239
+ var init_abi = __esm({
1240
+ "../../node_modules/viem/_esm/errors/abi.js"() {
1241
+ init_size();
1242
+ init_base();
1243
+ AbiEncodingArrayLengthMismatchError = class extends BaseError {
1244
+ constructor({ expectedLength, givenLength, type }) {
1245
+ super([
1246
+ `ABI encoding array length mismatch for type ${type}.`,
1247
+ `Expected length: ${expectedLength}`,
1248
+ `Given length: ${givenLength}`
1249
+ ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" });
1250
+ }
1251
+ };
1252
+ AbiEncodingBytesSizeMismatchError = class extends BaseError {
1253
+ constructor({ expectedSize, value }) {
1254
+ super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" });
1255
+ }
1256
+ };
1257
+ AbiEncodingLengthMismatchError = class extends BaseError {
1258
+ constructor({ expectedLength, givenLength }) {
1259
+ super([
1260
+ "ABI encoding params/values length mismatch.",
1261
+ `Expected length (params): ${expectedLength}`,
1262
+ `Given length (values): ${givenLength}`
1263
+ ].join("\n"), { name: "AbiEncodingLengthMismatchError" });
1264
+ }
1265
+ };
1266
+ BytesSizeMismatchError = class extends BaseError {
1267
+ constructor({ expectedSize, givenSize }) {
1268
+ super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {
1269
+ name: "BytesSizeMismatchError"
1270
+ });
1271
+ }
1272
+ };
1273
+ InvalidAbiEncodingTypeError = class extends BaseError {
1274
+ constructor(type, { docsPath }) {
1275
+ super([
1276
+ `Type "${type}" is not a valid encoding type.`,
1277
+ "Please provide a valid ABI type."
1278
+ ].join("\n"), { docsPath, name: "InvalidAbiEncodingType" });
1279
+ }
1280
+ };
1281
+ InvalidArrayError = class extends BaseError {
1282
+ constructor(value) {
1283
+ super([`Value "${value}" is not a valid array.`].join("\n"), {
1284
+ name: "InvalidArrayError"
1285
+ });
1286
+ }
1287
+ };
1288
+ }
1289
+ });
1290
+
1237
1291
  // ../../node_modules/viem/_esm/errors/data.js
1238
- var SizeExceedsPaddingSizeError;
1292
+ var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError;
1239
1293
  var init_data = __esm({
1240
1294
  "../../node_modules/viem/_esm/errors/data.js"() {
1241
1295
  init_base();
1296
+ SliceOffsetOutOfBoundsError = class extends BaseError {
1297
+ constructor({ offset, position, size: size2 }) {
1298
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" });
1299
+ }
1300
+ };
1242
1301
  SizeExceedsPaddingSizeError = class extends BaseError {
1243
1302
  constructor({ size: size2, targetSize, type }) {
1244
1303
  super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
@@ -1853,6 +1912,25 @@ var init_keccak256 = __esm({
1853
1912
  }
1854
1913
  });
1855
1914
 
1915
+ // ../../node_modules/viem/_esm/errors/address.js
1916
+ var InvalidAddressError2;
1917
+ var init_address = __esm({
1918
+ "../../node_modules/viem/_esm/errors/address.js"() {
1919
+ init_base();
1920
+ InvalidAddressError2 = class extends BaseError {
1921
+ constructor({ address }) {
1922
+ super(`Address "${address}" is invalid.`, {
1923
+ metaMessages: [
1924
+ "- Address must be a hex value of 20 bytes (40 hex characters).",
1925
+ "- Address must match its checksum counterpart."
1926
+ ],
1927
+ name: "InvalidAddressError"
1928
+ });
1929
+ }
1930
+ };
1931
+ }
1932
+ });
1933
+
1856
1934
  // ../../node_modules/viem/_esm/utils/lru.js
1857
1935
  var LruMap;
1858
1936
  var init_lru = __esm({
@@ -1920,6 +1998,374 @@ var init_getAddress = __esm({
1920
1998
  }
1921
1999
  });
1922
2000
 
2001
+ // ../../node_modules/viem/_esm/utils/address/isAddress.js
2002
+ function isAddress(address, options) {
2003
+ const { strict = true } = options ?? {};
2004
+ const cacheKey = `${address}.${strict}`;
2005
+ if (isAddressCache.has(cacheKey))
2006
+ return isAddressCache.get(cacheKey);
2007
+ const result = (() => {
2008
+ if (!addressRegex.test(address))
2009
+ return false;
2010
+ if (address.toLowerCase() === address)
2011
+ return true;
2012
+ if (strict)
2013
+ return checksumAddress(address) === address;
2014
+ return true;
2015
+ })();
2016
+ isAddressCache.set(cacheKey, result);
2017
+ return result;
2018
+ }
2019
+ var addressRegex, isAddressCache;
2020
+ var init_isAddress = __esm({
2021
+ "../../node_modules/viem/_esm/utils/address/isAddress.js"() {
2022
+ init_lru();
2023
+ init_getAddress();
2024
+ addressRegex = /^0x[a-fA-F0-9]{40}$/;
2025
+ isAddressCache = /* @__PURE__ */ new LruMap(8192);
2026
+ }
2027
+ });
2028
+
2029
+ // ../../node_modules/viem/_esm/utils/data/concat.js
2030
+ function concat(values) {
2031
+ if (typeof values[0] === "string")
2032
+ return concatHex(values);
2033
+ return concatBytes2(values);
2034
+ }
2035
+ function concatBytes2(values) {
2036
+ let length = 0;
2037
+ for (const arr of values) {
2038
+ length += arr.length;
2039
+ }
2040
+ const result = new Uint8Array(length);
2041
+ let offset = 0;
2042
+ for (const arr of values) {
2043
+ result.set(arr, offset);
2044
+ offset += arr.length;
2045
+ }
2046
+ return result;
2047
+ }
2048
+ function concatHex(values) {
2049
+ return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
2050
+ }
2051
+ var init_concat = __esm({
2052
+ "../../node_modules/viem/_esm/utils/data/concat.js"() {
2053
+ }
2054
+ });
2055
+
2056
+ // ../../node_modules/viem/_esm/utils/data/slice.js
2057
+ function slice(value, start, end, { strict } = {}) {
2058
+ if (isHex(value, { strict: false }))
2059
+ return sliceHex(value, start, end, {
2060
+ strict
2061
+ });
2062
+ return sliceBytes(value, start, end, {
2063
+ strict
2064
+ });
2065
+ }
2066
+ function assertStartOffset(value, start) {
2067
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
2068
+ throw new SliceOffsetOutOfBoundsError({
2069
+ offset: start,
2070
+ position: "start",
2071
+ size: size(value)
2072
+ });
2073
+ }
2074
+ function assertEndOffset(value, start, end) {
2075
+ if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) {
2076
+ throw new SliceOffsetOutOfBoundsError({
2077
+ offset: end,
2078
+ position: "end",
2079
+ size: size(value)
2080
+ });
2081
+ }
2082
+ }
2083
+ function sliceBytes(value_, start, end, { strict } = {}) {
2084
+ assertStartOffset(value_, start);
2085
+ const value = value_.slice(start, end);
2086
+ if (strict)
2087
+ assertEndOffset(value, start, end);
2088
+ return value;
2089
+ }
2090
+ function sliceHex(value_, start, end, { strict } = {}) {
2091
+ assertStartOffset(value_, start);
2092
+ const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
2093
+ if (strict)
2094
+ assertEndOffset(value, start, end);
2095
+ return value;
2096
+ }
2097
+ var init_slice = __esm({
2098
+ "../../node_modules/viem/_esm/utils/data/slice.js"() {
2099
+ init_data();
2100
+ init_isHex();
2101
+ init_size();
2102
+ }
2103
+ });
2104
+
2105
+ // ../../node_modules/viem/_esm/utils/regex.js
2106
+ var bytesRegex, integerRegex;
2107
+ var init_regex = __esm({
2108
+ "../../node_modules/viem/_esm/utils/regex.js"() {
2109
+ bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
2110
+ integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
2111
+ }
2112
+ });
2113
+
2114
+ // ../../node_modules/viem/_esm/utils/abi/encodeAbiParameters.js
2115
+ function encodeAbiParameters(params, values) {
2116
+ if (params.length !== values.length)
2117
+ throw new AbiEncodingLengthMismatchError({
2118
+ expectedLength: params.length,
2119
+ givenLength: values.length
2120
+ });
2121
+ const preparedParams = prepareParams({
2122
+ params,
2123
+ values
2124
+ });
2125
+ return encodeParams(preparedParams);
2126
+ }
2127
+ function prepareParams({ params, values }) {
2128
+ const preparedParams = [];
2129
+ for (let i = 0; i < params.length; i++) {
2130
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
2131
+ }
2132
+ return preparedParams;
2133
+ }
2134
+ function prepareParam({ param, value }) {
2135
+ const arrayComponents = getArrayComponents(param.type);
2136
+ if (arrayComponents) {
2137
+ const [length, type] = arrayComponents;
2138
+ return encodeArray(value, { length, param: { ...param, type } });
2139
+ }
2140
+ if (param.type === "tuple") {
2141
+ return encodeTuple(value, {
2142
+ param
2143
+ });
2144
+ }
2145
+ if (param.type === "address") {
2146
+ return encodeAddress(value);
2147
+ }
2148
+ if (param.type === "bool") {
2149
+ return encodeBool(value);
2150
+ }
2151
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
2152
+ const signed = param.type.startsWith("int");
2153
+ const [, , size2 = "256"] = integerRegex.exec(param.type) ?? [];
2154
+ return encodeNumber(value, {
2155
+ signed,
2156
+ size: Number(size2)
2157
+ });
2158
+ }
2159
+ if (param.type.startsWith("bytes")) {
2160
+ return encodeBytes(value, { param });
2161
+ }
2162
+ if (param.type === "string") {
2163
+ return encodeString(value);
2164
+ }
2165
+ throw new InvalidAbiEncodingTypeError(param.type, {
2166
+ docsPath: "/docs/contract/encodeAbiParameters"
2167
+ });
2168
+ }
2169
+ function encodeParams(preparedParams) {
2170
+ let staticSize = 0;
2171
+ for (let i = 0; i < preparedParams.length; i++) {
2172
+ const { dynamic, encoded } = preparedParams[i];
2173
+ if (dynamic)
2174
+ staticSize += 32;
2175
+ else
2176
+ staticSize += size(encoded);
2177
+ }
2178
+ const staticParams = [];
2179
+ const dynamicParams = [];
2180
+ let dynamicSize = 0;
2181
+ for (let i = 0; i < preparedParams.length; i++) {
2182
+ const { dynamic, encoded } = preparedParams[i];
2183
+ if (dynamic) {
2184
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
2185
+ dynamicParams.push(encoded);
2186
+ dynamicSize += size(encoded);
2187
+ } else {
2188
+ staticParams.push(encoded);
2189
+ }
2190
+ }
2191
+ return concatHex([...staticParams, ...dynamicParams]);
2192
+ }
2193
+ function encodeAddress(value) {
2194
+ if (!isAddress(value))
2195
+ throw new InvalidAddressError2({ address: value });
2196
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
2197
+ }
2198
+ function encodeArray(value, { length, param }) {
2199
+ const dynamic = length === null;
2200
+ if (!Array.isArray(value))
2201
+ throw new InvalidArrayError(value);
2202
+ if (!dynamic && value.length !== length)
2203
+ throw new AbiEncodingArrayLengthMismatchError({
2204
+ expectedLength: length,
2205
+ givenLength: value.length,
2206
+ type: `${param.type}[${length}]`
2207
+ });
2208
+ let dynamicChild = value.length === 0 && isDynamicType(param);
2209
+ const preparedParams = [];
2210
+ for (let i = 0; i < value.length; i++) {
2211
+ const preparedParam = prepareParam({ param, value: value[i] });
2212
+ if (preparedParam.dynamic)
2213
+ dynamicChild = true;
2214
+ preparedParams.push(preparedParam);
2215
+ }
2216
+ if (dynamic || dynamicChild) {
2217
+ const data = encodeParams(preparedParams);
2218
+ if (dynamic) {
2219
+ const length2 = numberToHex(preparedParams.length, { size: 32 });
2220
+ return {
2221
+ dynamic: true,
2222
+ encoded: concatHex([length2, data])
2223
+ };
2224
+ }
2225
+ if (dynamicChild)
2226
+ return { dynamic: true, encoded: data };
2227
+ }
2228
+ return {
2229
+ dynamic: false,
2230
+ encoded: concatHex(preparedParams.map(({ encoded }) => encoded))
2231
+ };
2232
+ }
2233
+ function encodeBytes(value, { param }) {
2234
+ const [, paramSize] = param.type.split("bytes");
2235
+ const bytesSize = size(value);
2236
+ if (!paramSize) {
2237
+ let value_ = value;
2238
+ if (bytesSize % 32 !== 0)
2239
+ value_ = padHex(value_, {
2240
+ dir: "right",
2241
+ size: Math.ceil((value.length - 2) / 2 / 32) * 32
2242
+ });
2243
+ return {
2244
+ dynamic: true,
2245
+ encoded: concatHex([
2246
+ padHex(numberToHex(bytesSize, { size: 32 })),
2247
+ value_
2248
+ ])
2249
+ };
2250
+ }
2251
+ if (bytesSize !== Number.parseInt(paramSize, 10))
2252
+ throw new AbiEncodingBytesSizeMismatchError({
2253
+ expectedSize: Number.parseInt(paramSize, 10),
2254
+ value
2255
+ });
2256
+ return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
2257
+ }
2258
+ function encodeBool(value) {
2259
+ if (typeof value !== "boolean")
2260
+ throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
2261
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
2262
+ }
2263
+ function encodeNumber(value, { signed, size: size2 = 256 }) {
2264
+ if (typeof size2 === "number") {
2265
+ const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n;
2266
+ const min = signed ? -max - 1n : 0n;
2267
+ if (value > max || value < min)
2268
+ throw new IntegerOutOfRangeError({
2269
+ max: max.toString(),
2270
+ min: min.toString(),
2271
+ signed,
2272
+ size: size2 / 8,
2273
+ value: value.toString()
2274
+ });
2275
+ }
2276
+ return {
2277
+ dynamic: false,
2278
+ encoded: numberToHex(value, {
2279
+ size: 32,
2280
+ signed
2281
+ })
2282
+ };
2283
+ }
2284
+ function encodeString(value) {
2285
+ const hexValue = stringToHex(value);
2286
+ const partsLength = Math.ceil(size(hexValue) / 32);
2287
+ const parts = [];
2288
+ for (let i = 0; i < partsLength; i++) {
2289
+ parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
2290
+ dir: "right"
2291
+ }));
2292
+ }
2293
+ return {
2294
+ dynamic: true,
2295
+ encoded: concatHex([
2296
+ padHex(numberToHex(size(hexValue), { size: 32 })),
2297
+ ...parts
2298
+ ])
2299
+ };
2300
+ }
2301
+ function encodeTuple(value, { param }) {
2302
+ let dynamic = false;
2303
+ const preparedParams = [];
2304
+ for (let i = 0; i < param.components.length; i++) {
2305
+ const param_ = param.components[i];
2306
+ const index = Array.isArray(value) ? i : param_.name;
2307
+ const preparedParam = prepareParam({
2308
+ param: param_,
2309
+ value: value[index]
2310
+ });
2311
+ preparedParams.push(preparedParam);
2312
+ if (preparedParam.dynamic)
2313
+ dynamic = true;
2314
+ }
2315
+ return {
2316
+ dynamic,
2317
+ encoded: dynamic ? encodeParams(preparedParams) : concatHex(preparedParams.map(({ encoded }) => encoded))
2318
+ };
2319
+ }
2320
+ function getArrayComponents(type) {
2321
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
2322
+ return matches ? (
2323
+ // Return `null` if the array is dynamic.
2324
+ [matches[2] ? Number(matches[2]) : null, matches[1]]
2325
+ ) : void 0;
2326
+ }
2327
+ function isDynamicType(param) {
2328
+ const { type } = param;
2329
+ if (type === "string")
2330
+ return true;
2331
+ if (type === "bytes")
2332
+ return true;
2333
+ if (type.endsWith("[]"))
2334
+ return true;
2335
+ if (type === "tuple")
2336
+ return param.components.some(isDynamicType);
2337
+ const arrayComponents = getArrayComponents(type);
2338
+ if (arrayComponents)
2339
+ return isDynamicType({ ...param, type: arrayComponents[1] });
2340
+ return false;
2341
+ }
2342
+ var init_encodeAbiParameters = __esm({
2343
+ "../../node_modules/viem/_esm/utils/abi/encodeAbiParameters.js"() {
2344
+ init_abi();
2345
+ init_address();
2346
+ init_base();
2347
+ init_encoding();
2348
+ init_isAddress();
2349
+ init_concat();
2350
+ init_pad();
2351
+ init_size();
2352
+ init_slice();
2353
+ init_toHex();
2354
+ init_regex();
2355
+ }
2356
+ });
2357
+
2358
+ // ../../node_modules/viem/_esm/utils/stringify.js
2359
+ var stringify;
2360
+ var init_stringify = __esm({
2361
+ "../../node_modules/viem/_esm/utils/stringify.js"() {
2362
+ stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => {
2363
+ const value2 = typeof value_ === "bigint" ? value_.toString() : value_;
2364
+ return typeof replacer === "function" ? replacer(key, value2) : value2;
2365
+ }, space);
2366
+ }
2367
+ });
2368
+
1923
2369
  // ../../node_modules/viem/_esm/utils/unit/Value.js
1924
2370
  function format(value, decimals = 0) {
1925
2371
  if (!Number.isInteger(decimals) || decimals < 0)
@@ -2392,7 +2838,7 @@ function ensureBytes(title, hex, expectedLength) {
2392
2838
  throw new Error(title + " of length " + expectedLength + " expected, got " + len);
2393
2839
  return res;
2394
2840
  }
2395
- function concatBytes2(...arrays) {
2841
+ function concatBytes3(...arrays) {
2396
2842
  let sum = 0;
2397
2843
  for (let i = 0; i < arrays.length; i++) {
2398
2844
  const a = arrays[i];
@@ -2460,7 +2906,7 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
2460
2906
  out.push(sl);
2461
2907
  len += v.length;
2462
2908
  }
2463
- return concatBytes2(...out);
2909
+ return concatBytes3(...out);
2464
2910
  };
2465
2911
  const genUntil = (seed, pred) => {
2466
2912
  reset();
@@ -3092,7 +3538,7 @@ function weierstrassPoints(opts) {
3092
3538
  const Fn = Field(CURVE.n, CURVE.nBitLength);
3093
3539
  const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => {
3094
3540
  const a = point.toAffine();
3095
- return concatBytes2(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
3541
+ return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
3096
3542
  });
3097
3543
  const fromBytes = CURVE.fromBytes || ((bytes) => {
3098
3544
  const tail = bytes.subarray(1);
@@ -3518,7 +3964,7 @@ function weierstrass(curveDef) {
3518
3964
  toBytes(_c, point, isCompressed) {
3519
3965
  const a = point.toAffine();
3520
3966
  const x = Fp.toBytes(a.x);
3521
- const cat = concatBytes2;
3967
+ const cat = concatBytes3;
3522
3968
  abool("isCompressed", isCompressed);
3523
3969
  if (isCompressed) {
3524
3970
  return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
@@ -3731,7 +4177,7 @@ function weierstrass(curveDef) {
3731
4177
  const e = ent === true ? randomBytes4(Fp.BYTES) : ent;
3732
4178
  seedArgs.push(ensureBytes("extraEntropy", e));
3733
4179
  }
3734
- const seed = concatBytes2(...seedArgs);
4180
+ const seed = concatBytes3(...seedArgs);
3735
4181
  const m = h1int;
3736
4182
  function k2sig(kBytes) {
3737
4183
  const k = bits2int(kBytes);
@@ -4094,22 +4540,22 @@ function expand_message_xmd(msg, DST, lenInBytes, H) {
4094
4540
  abytes2(DST);
4095
4541
  anum(lenInBytes);
4096
4542
  if (DST.length > 255)
4097
- DST = H(concatBytes2(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST));
4543
+ DST = H(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST));
4098
4544
  const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
4099
4545
  const ell = Math.ceil(lenInBytes / b_in_bytes);
4100
4546
  if (lenInBytes > 65535 || ell > 255)
4101
4547
  throw new Error("expand_message_xmd: invalid lenInBytes");
4102
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
4548
+ const DST_prime = concatBytes3(DST, i2osp(DST.length, 1));
4103
4549
  const Z_pad = i2osp(0, r_in_bytes);
4104
4550
  const l_i_b_str = i2osp(lenInBytes, 2);
4105
4551
  const b = new Array(ell);
4106
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
4107
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
4552
+ const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
4553
+ b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime));
4108
4554
  for (let i = 1; i <= ell; i++) {
4109
4555
  const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
4110
- b[i] = H(concatBytes2(...args));
4556
+ b[i] = H(concatBytes3(...args));
4111
4557
  }
4112
- const pseudo_random_bytes = concatBytes2(...b);
4558
+ const pseudo_random_bytes = concatBytes3(...b);
4113
4559
  return pseudo_random_bytes.slice(0, lenInBytes);
4114
4560
  }
4115
4561
  function expand_message_xof(msg, DST, lenInBytes, k, H) {
@@ -4255,10 +4701,10 @@ function taggedHash(tag, ...messages) {
4255
4701
  let tagP = TAGGED_HASH_PREFIXES[tag];
4256
4702
  if (tagP === void 0) {
4257
4703
  const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
4258
- tagP = concatBytes2(tagH, tagH);
4704
+ tagP = concatBytes3(tagH, tagH);
4259
4705
  TAGGED_HASH_PREFIXES[tag] = tagP;
4260
4706
  }
4261
- return sha256(concatBytes2(tagP, ...messages));
4707
+ return sha256(concatBytes3(tagP, ...messages));
4262
4708
  }
4263
4709
  function schnorrGetExtPubKey(priv) {
4264
4710
  let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
@@ -4372,82 +4818,1791 @@ var init_secp256k1 = __esm({
4372
4818
  if (k1 > POW_2_128 || k2 > POW_2_128) {
4373
4819
  throw new Error("splitScalar: Endomorphism failed, k=" + k);
4374
4820
  }
4375
- return { k1neg, k1, k2neg, k2 };
4821
+ return { k1neg, k1, k2neg, k2 };
4822
+ }
4823
+ }
4824
+ }, sha256);
4825
+ TAGGED_HASH_PREFIXES = {};
4826
+ pointToBytes = (point) => point.toRawBytes(true).slice(1);
4827
+ numTo32b = (n) => numberToBytesBE(n, 32);
4828
+ modP = (x) => mod(x, secp256k1P);
4829
+ modN = (x) => mod(x, secp256k1N);
4830
+ Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();
4831
+ GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
4832
+ num = bytesToNumberBE;
4833
+ schnorr = /* @__PURE__ */ (() => ({
4834
+ getPublicKey: schnorrGetPublicKey,
4835
+ sign: schnorrSign,
4836
+ verify: schnorrVerify,
4837
+ utils: {
4838
+ randomPrivateKey: secp256k1.utils.randomPrivateKey,
4839
+ lift_x,
4840
+ pointToBytes,
4841
+ numberToBytesBE,
4842
+ bytesToNumberBE,
4843
+ taggedHash,
4844
+ mod
4845
+ }
4846
+ }))();
4847
+ isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
4848
+ // xNum
4849
+ [
4850
+ "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
4851
+ "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
4852
+ "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
4853
+ "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
4854
+ ],
4855
+ // xDen
4856
+ [
4857
+ "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
4858
+ "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
4859
+ "0x0000000000000000000000000000000000000000000000000000000000000001"
4860
+ // LAST 1
4861
+ ],
4862
+ // yNum
4863
+ [
4864
+ "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
4865
+ "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
4866
+ "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
4867
+ "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
4868
+ ],
4869
+ // yDen
4870
+ [
4871
+ "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
4872
+ "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
4873
+ "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
4874
+ "0x0000000000000000000000000000000000000000000000000000000000000001"
4875
+ // LAST 1
4876
+ ]
4877
+ ].map((i) => i.map((j) => BigInt(j)))))();
4878
+ mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
4879
+ A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
4880
+ B: BigInt("1771"),
4881
+ Z: Fpk1.create(BigInt("-11"))
4882
+ }))();
4883
+ secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => {
4884
+ const { x, y } = mapSWU(Fpk1.create(scalars[0]));
4885
+ return isoMap(x, y);
4886
+ }, {
4887
+ DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
4888
+ encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
4889
+ p: Fpk1.ORDER,
4890
+ m: 1,
4891
+ k: 128,
4892
+ expand: "xmd",
4893
+ hash: sha256
4894
+ }))();
4895
+ hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
4896
+ encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
4897
+ }
4898
+ });
4899
+
4900
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/utils/utf8.cjs
4901
+ var require_utf8 = __commonJS({
4902
+ "../../node_modules/@msgpack/msgpack/dist.cjs/utils/utf8.cjs"(exports) {
4903
+ "use strict";
4904
+ Object.defineProperty(exports, "__esModule", { value: true });
4905
+ exports.utf8Count = utf8Count;
4906
+ exports.utf8EncodeJs = utf8EncodeJs;
4907
+ exports.utf8EncodeTE = utf8EncodeTE;
4908
+ exports.utf8Encode = utf8Encode;
4909
+ exports.utf8DecodeJs = utf8DecodeJs;
4910
+ exports.utf8DecodeTD = utf8DecodeTD;
4911
+ exports.utf8Decode = utf8Decode;
4912
+ function utf8Count(str2) {
4913
+ const strLength = str2.length;
4914
+ let byteLength = 0;
4915
+ let pos = 0;
4916
+ while (pos < strLength) {
4917
+ let value = str2.charCodeAt(pos++);
4918
+ if ((value & 4294967168) === 0) {
4919
+ byteLength++;
4920
+ continue;
4921
+ } else if ((value & 4294965248) === 0) {
4922
+ byteLength += 2;
4923
+ } else {
4924
+ if (value >= 55296 && value <= 56319) {
4925
+ if (pos < strLength) {
4926
+ const extra = str2.charCodeAt(pos);
4927
+ if ((extra & 64512) === 56320) {
4928
+ ++pos;
4929
+ value = ((value & 1023) << 10) + (extra & 1023) + 65536;
4930
+ }
4931
+ }
4932
+ }
4933
+ if ((value & 4294901760) === 0) {
4934
+ byteLength += 3;
4935
+ } else {
4936
+ byteLength += 4;
4937
+ }
4938
+ }
4939
+ }
4940
+ return byteLength;
4941
+ }
4942
+ function utf8EncodeJs(str2, output, outputOffset) {
4943
+ const strLength = str2.length;
4944
+ let offset = outputOffset;
4945
+ let pos = 0;
4946
+ while (pos < strLength) {
4947
+ let value = str2.charCodeAt(pos++);
4948
+ if ((value & 4294967168) === 0) {
4949
+ output[offset++] = value;
4950
+ continue;
4951
+ } else if ((value & 4294965248) === 0) {
4952
+ output[offset++] = value >> 6 & 31 | 192;
4953
+ } else {
4954
+ if (value >= 55296 && value <= 56319) {
4955
+ if (pos < strLength) {
4956
+ const extra = str2.charCodeAt(pos);
4957
+ if ((extra & 64512) === 56320) {
4958
+ ++pos;
4959
+ value = ((value & 1023) << 10) + (extra & 1023) + 65536;
4960
+ }
4961
+ }
4962
+ }
4963
+ if ((value & 4294901760) === 0) {
4964
+ output[offset++] = value >> 12 & 15 | 224;
4965
+ output[offset++] = value >> 6 & 63 | 128;
4966
+ } else {
4967
+ output[offset++] = value >> 18 & 7 | 240;
4968
+ output[offset++] = value >> 12 & 63 | 128;
4969
+ output[offset++] = value >> 6 & 63 | 128;
4970
+ }
4971
+ }
4972
+ output[offset++] = value & 63 | 128;
4973
+ }
4974
+ }
4975
+ var sharedTextEncoder = new TextEncoder();
4976
+ var TEXT_ENCODER_THRESHOLD = 50;
4977
+ function utf8EncodeTE(str2, output, outputOffset) {
4978
+ sharedTextEncoder.encodeInto(str2, output.subarray(outputOffset));
4979
+ }
4980
+ function utf8Encode(str2, output, outputOffset) {
4981
+ if (str2.length > TEXT_ENCODER_THRESHOLD) {
4982
+ utf8EncodeTE(str2, output, outputOffset);
4983
+ } else {
4984
+ utf8EncodeJs(str2, output, outputOffset);
4985
+ }
4986
+ }
4987
+ var CHUNK_SIZE = 4096;
4988
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
4989
+ let offset = inputOffset;
4990
+ const end = offset + byteLength;
4991
+ const units = [];
4992
+ let result = "";
4993
+ while (offset < end) {
4994
+ const byte1 = bytes[offset++];
4995
+ if ((byte1 & 128) === 0) {
4996
+ units.push(byte1);
4997
+ } else if ((byte1 & 224) === 192) {
4998
+ const byte2 = bytes[offset++] & 63;
4999
+ units.push((byte1 & 31) << 6 | byte2);
5000
+ } else if ((byte1 & 240) === 224) {
5001
+ const byte2 = bytes[offset++] & 63;
5002
+ const byte3 = bytes[offset++] & 63;
5003
+ units.push((byte1 & 31) << 12 | byte2 << 6 | byte3);
5004
+ } else if ((byte1 & 248) === 240) {
5005
+ const byte2 = bytes[offset++] & 63;
5006
+ const byte3 = bytes[offset++] & 63;
5007
+ const byte4 = bytes[offset++] & 63;
5008
+ let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4;
5009
+ if (unit > 65535) {
5010
+ unit -= 65536;
5011
+ units.push(unit >>> 10 & 1023 | 55296);
5012
+ unit = 56320 | unit & 1023;
5013
+ }
5014
+ units.push(unit);
5015
+ } else {
5016
+ units.push(byte1);
5017
+ }
5018
+ if (units.length >= CHUNK_SIZE) {
5019
+ result += String.fromCharCode(...units);
5020
+ units.length = 0;
5021
+ }
5022
+ }
5023
+ if (units.length > 0) {
5024
+ result += String.fromCharCode(...units);
5025
+ }
5026
+ return result;
5027
+ }
5028
+ var sharedTextDecoder = new TextDecoder();
5029
+ var TEXT_DECODER_THRESHOLD = 200;
5030
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
5031
+ const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
5032
+ return sharedTextDecoder.decode(stringBytes);
5033
+ }
5034
+ function utf8Decode(bytes, inputOffset, byteLength) {
5035
+ if (byteLength > TEXT_DECODER_THRESHOLD) {
5036
+ return utf8DecodeTD(bytes, inputOffset, byteLength);
5037
+ } else {
5038
+ return utf8DecodeJs(bytes, inputOffset, byteLength);
5039
+ }
5040
+ }
5041
+ }
5042
+ });
5043
+
5044
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/ExtData.cjs
5045
+ var require_ExtData = __commonJS({
5046
+ "../../node_modules/@msgpack/msgpack/dist.cjs/ExtData.cjs"(exports) {
5047
+ "use strict";
5048
+ Object.defineProperty(exports, "__esModule", { value: true });
5049
+ exports.ExtData = void 0;
5050
+ var ExtData = class {
5051
+ type;
5052
+ data;
5053
+ constructor(type, data) {
5054
+ this.type = type;
5055
+ this.data = data;
5056
+ }
5057
+ };
5058
+ exports.ExtData = ExtData;
5059
+ }
5060
+ });
5061
+
5062
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/DecodeError.cjs
5063
+ var require_DecodeError = __commonJS({
5064
+ "../../node_modules/@msgpack/msgpack/dist.cjs/DecodeError.cjs"(exports) {
5065
+ "use strict";
5066
+ Object.defineProperty(exports, "__esModule", { value: true });
5067
+ exports.DecodeError = void 0;
5068
+ var DecodeError = class _DecodeError extends Error {
5069
+ constructor(message) {
5070
+ super(message);
5071
+ const proto = Object.create(_DecodeError.prototype);
5072
+ Object.setPrototypeOf(this, proto);
5073
+ Object.defineProperty(this, "name", {
5074
+ configurable: true,
5075
+ enumerable: false,
5076
+ value: _DecodeError.name
5077
+ });
5078
+ }
5079
+ };
5080
+ exports.DecodeError = DecodeError;
5081
+ }
5082
+ });
5083
+
5084
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/utils/int.cjs
5085
+ var require_int = __commonJS({
5086
+ "../../node_modules/@msgpack/msgpack/dist.cjs/utils/int.cjs"(exports) {
5087
+ "use strict";
5088
+ Object.defineProperty(exports, "__esModule", { value: true });
5089
+ exports.UINT32_MAX = void 0;
5090
+ exports.setUint64 = setUint64;
5091
+ exports.setInt64 = setInt64;
5092
+ exports.getInt64 = getInt64;
5093
+ exports.getUint64 = getUint64;
5094
+ exports.UINT32_MAX = 4294967295;
5095
+ function setUint64(view, offset, value) {
5096
+ const high = value / 4294967296;
5097
+ const low = value;
5098
+ view.setUint32(offset, high);
5099
+ view.setUint32(offset + 4, low);
5100
+ }
5101
+ function setInt64(view, offset, value) {
5102
+ const high = Math.floor(value / 4294967296);
5103
+ const low = value;
5104
+ view.setUint32(offset, high);
5105
+ view.setUint32(offset + 4, low);
5106
+ }
5107
+ function getInt64(view, offset) {
5108
+ const high = view.getInt32(offset);
5109
+ const low = view.getUint32(offset + 4);
5110
+ return high * 4294967296 + low;
5111
+ }
5112
+ function getUint64(view, offset) {
5113
+ const high = view.getUint32(offset);
5114
+ const low = view.getUint32(offset + 4);
5115
+ return high * 4294967296 + low;
5116
+ }
5117
+ }
5118
+ });
5119
+
5120
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/timestamp.cjs
5121
+ var require_timestamp = __commonJS({
5122
+ "../../node_modules/@msgpack/msgpack/dist.cjs/timestamp.cjs"(exports) {
5123
+ "use strict";
5124
+ Object.defineProperty(exports, "__esModule", { value: true });
5125
+ exports.timestampExtension = exports.EXT_TIMESTAMP = void 0;
5126
+ exports.encodeTimeSpecToTimestamp = encodeTimeSpecToTimestamp;
5127
+ exports.encodeDateToTimeSpec = encodeDateToTimeSpec;
5128
+ exports.encodeTimestampExtension = encodeTimestampExtension;
5129
+ exports.decodeTimestampToTimeSpec = decodeTimestampToTimeSpec;
5130
+ exports.decodeTimestampExtension = decodeTimestampExtension;
5131
+ var DecodeError_ts_1 = require_DecodeError();
5132
+ var int_ts_1 = require_int();
5133
+ exports.EXT_TIMESTAMP = -1;
5134
+ var TIMESTAMP32_MAX_SEC = 4294967296 - 1;
5135
+ var TIMESTAMP64_MAX_SEC = 17179869184 - 1;
5136
+ function encodeTimeSpecToTimestamp({ sec, nsec }) {
5137
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
5138
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
5139
+ const rv = new Uint8Array(4);
5140
+ const view = new DataView(rv.buffer);
5141
+ view.setUint32(0, sec);
5142
+ return rv;
5143
+ } else {
5144
+ const secHigh = sec / 4294967296;
5145
+ const secLow = sec & 4294967295;
5146
+ const rv = new Uint8Array(8);
5147
+ const view = new DataView(rv.buffer);
5148
+ view.setUint32(0, nsec << 2 | secHigh & 3);
5149
+ view.setUint32(4, secLow);
5150
+ return rv;
5151
+ }
5152
+ } else {
5153
+ const rv = new Uint8Array(12);
5154
+ const view = new DataView(rv.buffer);
5155
+ view.setUint32(0, nsec);
5156
+ (0, int_ts_1.setInt64)(view, 4, sec);
5157
+ return rv;
5158
+ }
5159
+ }
5160
+ function encodeDateToTimeSpec(date) {
5161
+ const msec = date.getTime();
5162
+ const sec = Math.floor(msec / 1e3);
5163
+ const nsec = (msec - sec * 1e3) * 1e6;
5164
+ const nsecInSec = Math.floor(nsec / 1e9);
5165
+ return {
5166
+ sec: sec + nsecInSec,
5167
+ nsec: nsec - nsecInSec * 1e9
5168
+ };
5169
+ }
5170
+ function encodeTimestampExtension(object) {
5171
+ if (object instanceof Date) {
5172
+ const timeSpec = encodeDateToTimeSpec(object);
5173
+ return encodeTimeSpecToTimestamp(timeSpec);
5174
+ } else {
5175
+ return null;
5176
+ }
5177
+ }
5178
+ function decodeTimestampToTimeSpec(data) {
5179
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
5180
+ switch (data.byteLength) {
5181
+ case 4: {
5182
+ const sec = view.getUint32(0);
5183
+ const nsec = 0;
5184
+ return { sec, nsec };
5185
+ }
5186
+ case 8: {
5187
+ const nsec30AndSecHigh2 = view.getUint32(0);
5188
+ const secLow32 = view.getUint32(4);
5189
+ const sec = (nsec30AndSecHigh2 & 3) * 4294967296 + secLow32;
5190
+ const nsec = nsec30AndSecHigh2 >>> 2;
5191
+ return { sec, nsec };
5192
+ }
5193
+ case 12: {
5194
+ const sec = (0, int_ts_1.getInt64)(view, 4);
5195
+ const nsec = view.getUint32(0);
5196
+ return { sec, nsec };
5197
+ }
5198
+ default:
5199
+ throw new DecodeError_ts_1.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
5200
+ }
5201
+ }
5202
+ function decodeTimestampExtension(data) {
5203
+ const timeSpec = decodeTimestampToTimeSpec(data);
5204
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
5205
+ }
5206
+ exports.timestampExtension = {
5207
+ type: exports.EXT_TIMESTAMP,
5208
+ encode: encodeTimestampExtension,
5209
+ decode: decodeTimestampExtension
5210
+ };
5211
+ }
5212
+ });
5213
+
5214
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/ExtensionCodec.cjs
5215
+ var require_ExtensionCodec = __commonJS({
5216
+ "../../node_modules/@msgpack/msgpack/dist.cjs/ExtensionCodec.cjs"(exports) {
5217
+ "use strict";
5218
+ Object.defineProperty(exports, "__esModule", { value: true });
5219
+ exports.ExtensionCodec = void 0;
5220
+ var ExtData_ts_1 = require_ExtData();
5221
+ var timestamp_ts_1 = require_timestamp();
5222
+ var ExtensionCodec = class _ExtensionCodec {
5223
+ static defaultCodec = new _ExtensionCodec();
5224
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
5225
+ // this will make type errors a lot more clear
5226
+ // eslint-disable-next-line @typescript-eslint/naming-convention
5227
+ __brand;
5228
+ // built-in extensions
5229
+ builtInEncoders = [];
5230
+ builtInDecoders = [];
5231
+ // custom extensions
5232
+ encoders = [];
5233
+ decoders = [];
5234
+ constructor() {
5235
+ this.register(timestamp_ts_1.timestampExtension);
5236
+ }
5237
+ register({ type, encode, decode }) {
5238
+ if (type >= 0) {
5239
+ this.encoders[type] = encode;
5240
+ this.decoders[type] = decode;
5241
+ } else {
5242
+ const index = -1 - type;
5243
+ this.builtInEncoders[index] = encode;
5244
+ this.builtInDecoders[index] = decode;
5245
+ }
5246
+ }
5247
+ tryToEncode(object, context) {
5248
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
5249
+ const encodeExt = this.builtInEncoders[i];
5250
+ if (encodeExt != null) {
5251
+ const data = encodeExt(object, context);
5252
+ if (data != null) {
5253
+ const type = -1 - i;
5254
+ return new ExtData_ts_1.ExtData(type, data);
5255
+ }
5256
+ }
5257
+ }
5258
+ for (let i = 0; i < this.encoders.length; i++) {
5259
+ const encodeExt = this.encoders[i];
5260
+ if (encodeExt != null) {
5261
+ const data = encodeExt(object, context);
5262
+ if (data != null) {
5263
+ const type = i;
5264
+ return new ExtData_ts_1.ExtData(type, data);
5265
+ }
5266
+ }
5267
+ }
5268
+ if (object instanceof ExtData_ts_1.ExtData) {
5269
+ return object;
5270
+ }
5271
+ return null;
5272
+ }
5273
+ decode(data, type, context) {
5274
+ const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
5275
+ if (decodeExt) {
5276
+ return decodeExt(data, type, context);
5277
+ } else {
5278
+ return new ExtData_ts_1.ExtData(type, data);
5279
+ }
5280
+ }
5281
+ };
5282
+ exports.ExtensionCodec = ExtensionCodec;
5283
+ }
5284
+ });
5285
+
5286
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/utils/typedArrays.cjs
5287
+ var require_typedArrays = __commonJS({
5288
+ "../../node_modules/@msgpack/msgpack/dist.cjs/utils/typedArrays.cjs"(exports) {
5289
+ "use strict";
5290
+ Object.defineProperty(exports, "__esModule", { value: true });
5291
+ exports.ensureUint8Array = ensureUint8Array;
5292
+ function isArrayBufferLike(buffer) {
5293
+ return buffer instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer;
5294
+ }
5295
+ function ensureUint8Array(buffer) {
5296
+ if (buffer instanceof Uint8Array) {
5297
+ return buffer;
5298
+ } else if (ArrayBuffer.isView(buffer)) {
5299
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
5300
+ } else if (isArrayBufferLike(buffer)) {
5301
+ return new Uint8Array(buffer);
5302
+ } else {
5303
+ return Uint8Array.from(buffer);
5304
+ }
5305
+ }
5306
+ }
5307
+ });
5308
+
5309
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/Encoder.cjs
5310
+ var require_Encoder = __commonJS({
5311
+ "../../node_modules/@msgpack/msgpack/dist.cjs/Encoder.cjs"(exports) {
5312
+ "use strict";
5313
+ Object.defineProperty(exports, "__esModule", { value: true });
5314
+ exports.Encoder = exports.DEFAULT_INITIAL_BUFFER_SIZE = exports.DEFAULT_MAX_DEPTH = void 0;
5315
+ var utf8_ts_1 = require_utf8();
5316
+ var ExtensionCodec_ts_1 = require_ExtensionCodec();
5317
+ var int_ts_1 = require_int();
5318
+ var typedArrays_ts_1 = require_typedArrays();
5319
+ exports.DEFAULT_MAX_DEPTH = 100;
5320
+ exports.DEFAULT_INITIAL_BUFFER_SIZE = 2048;
5321
+ var Encoder = class _Encoder {
5322
+ extensionCodec;
5323
+ context;
5324
+ useBigInt64;
5325
+ maxDepth;
5326
+ initialBufferSize;
5327
+ sortKeys;
5328
+ forceFloat32;
5329
+ ignoreUndefined;
5330
+ forceIntegerToFloat;
5331
+ pos;
5332
+ view;
5333
+ bytes;
5334
+ entered = false;
5335
+ constructor(options) {
5336
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec_ts_1.ExtensionCodec.defaultCodec;
5337
+ this.context = options?.context;
5338
+ this.useBigInt64 = options?.useBigInt64 ?? false;
5339
+ this.maxDepth = options?.maxDepth ?? exports.DEFAULT_MAX_DEPTH;
5340
+ this.initialBufferSize = options?.initialBufferSize ?? exports.DEFAULT_INITIAL_BUFFER_SIZE;
5341
+ this.sortKeys = options?.sortKeys ?? false;
5342
+ this.forceFloat32 = options?.forceFloat32 ?? false;
5343
+ this.ignoreUndefined = options?.ignoreUndefined ?? false;
5344
+ this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
5345
+ this.pos = 0;
5346
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
5347
+ this.bytes = new Uint8Array(this.view.buffer);
5348
+ }
5349
+ clone() {
5350
+ return new _Encoder({
5351
+ extensionCodec: this.extensionCodec,
5352
+ context: this.context,
5353
+ useBigInt64: this.useBigInt64,
5354
+ maxDepth: this.maxDepth,
5355
+ initialBufferSize: this.initialBufferSize,
5356
+ sortKeys: this.sortKeys,
5357
+ forceFloat32: this.forceFloat32,
5358
+ ignoreUndefined: this.ignoreUndefined,
5359
+ forceIntegerToFloat: this.forceIntegerToFloat
5360
+ });
5361
+ }
5362
+ reinitializeState() {
5363
+ this.pos = 0;
5364
+ }
5365
+ /**
5366
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
5367
+ *
5368
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
5369
+ */
5370
+ encodeSharedRef(object) {
5371
+ if (this.entered) {
5372
+ const instance = this.clone();
5373
+ return instance.encodeSharedRef(object);
5374
+ }
5375
+ try {
5376
+ this.entered = true;
5377
+ this.reinitializeState();
5378
+ this.doEncode(object, 1);
5379
+ return this.bytes.subarray(0, this.pos);
5380
+ } finally {
5381
+ this.entered = false;
5382
+ }
5383
+ }
5384
+ /**
5385
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
5386
+ */
5387
+ encode(object) {
5388
+ if (this.entered) {
5389
+ const instance = this.clone();
5390
+ return instance.encode(object);
5391
+ }
5392
+ try {
5393
+ this.entered = true;
5394
+ this.reinitializeState();
5395
+ this.doEncode(object, 1);
5396
+ return this.bytes.slice(0, this.pos);
5397
+ } finally {
5398
+ this.entered = false;
5399
+ }
5400
+ }
5401
+ doEncode(object, depth) {
5402
+ if (depth > this.maxDepth) {
5403
+ throw new Error(`Too deep objects in depth ${depth}`);
5404
+ }
5405
+ if (object == null) {
5406
+ this.encodeNil();
5407
+ } else if (typeof object === "boolean") {
5408
+ this.encodeBoolean(object);
5409
+ } else if (typeof object === "number") {
5410
+ if (!this.forceIntegerToFloat) {
5411
+ this.encodeNumber(object);
5412
+ } else {
5413
+ this.encodeNumberAsFloat(object);
5414
+ }
5415
+ } else if (typeof object === "string") {
5416
+ this.encodeString(object);
5417
+ } else if (this.useBigInt64 && typeof object === "bigint") {
5418
+ this.encodeBigInt64(object);
5419
+ } else {
5420
+ this.encodeObject(object, depth);
5421
+ }
5422
+ }
5423
+ ensureBufferSizeToWrite(sizeToWrite) {
5424
+ const requiredSize = this.pos + sizeToWrite;
5425
+ if (this.view.byteLength < requiredSize) {
5426
+ this.resizeBuffer(requiredSize * 2);
5427
+ }
5428
+ }
5429
+ resizeBuffer(newSize) {
5430
+ const newBuffer = new ArrayBuffer(newSize);
5431
+ const newBytes = new Uint8Array(newBuffer);
5432
+ const newView = new DataView(newBuffer);
5433
+ newBytes.set(this.bytes);
5434
+ this.view = newView;
5435
+ this.bytes = newBytes;
5436
+ }
5437
+ encodeNil() {
5438
+ this.writeU8(192);
5439
+ }
5440
+ encodeBoolean(object) {
5441
+ if (object === false) {
5442
+ this.writeU8(194);
5443
+ } else {
5444
+ this.writeU8(195);
5445
+ }
5446
+ }
5447
+ encodeNumber(object) {
5448
+ if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
5449
+ if (object >= 0) {
5450
+ if (object < 128) {
5451
+ this.writeU8(object);
5452
+ } else if (object < 256) {
5453
+ this.writeU8(204);
5454
+ this.writeU8(object);
5455
+ } else if (object < 65536) {
5456
+ this.writeU8(205);
5457
+ this.writeU16(object);
5458
+ } else if (object < 4294967296) {
5459
+ this.writeU8(206);
5460
+ this.writeU32(object);
5461
+ } else if (!this.useBigInt64) {
5462
+ this.writeU8(207);
5463
+ this.writeU64(object);
5464
+ } else {
5465
+ this.encodeNumberAsFloat(object);
5466
+ }
5467
+ } else {
5468
+ if (object >= -32) {
5469
+ this.writeU8(224 | object + 32);
5470
+ } else if (object >= -128) {
5471
+ this.writeU8(208);
5472
+ this.writeI8(object);
5473
+ } else if (object >= -32768) {
5474
+ this.writeU8(209);
5475
+ this.writeI16(object);
5476
+ } else if (object >= -2147483648) {
5477
+ this.writeU8(210);
5478
+ this.writeI32(object);
5479
+ } else if (!this.useBigInt64) {
5480
+ this.writeU8(211);
5481
+ this.writeI64(object);
5482
+ } else {
5483
+ this.encodeNumberAsFloat(object);
5484
+ }
5485
+ }
5486
+ } else {
5487
+ this.encodeNumberAsFloat(object);
5488
+ }
5489
+ }
5490
+ encodeNumberAsFloat(object) {
5491
+ if (this.forceFloat32) {
5492
+ this.writeU8(202);
5493
+ this.writeF32(object);
5494
+ } else {
5495
+ this.writeU8(203);
5496
+ this.writeF64(object);
5497
+ }
5498
+ }
5499
+ encodeBigInt64(object) {
5500
+ if (object >= BigInt(0)) {
5501
+ this.writeU8(207);
5502
+ this.writeBigUint64(object);
5503
+ } else {
5504
+ this.writeU8(211);
5505
+ this.writeBigInt64(object);
5506
+ }
5507
+ }
5508
+ writeStringHeader(byteLength) {
5509
+ if (byteLength < 32) {
5510
+ this.writeU8(160 + byteLength);
5511
+ } else if (byteLength < 256) {
5512
+ this.writeU8(217);
5513
+ this.writeU8(byteLength);
5514
+ } else if (byteLength < 65536) {
5515
+ this.writeU8(218);
5516
+ this.writeU16(byteLength);
5517
+ } else if (byteLength < 4294967296) {
5518
+ this.writeU8(219);
5519
+ this.writeU32(byteLength);
5520
+ } else {
5521
+ throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
5522
+ }
5523
+ }
5524
+ encodeString(object) {
5525
+ const maxHeaderSize = 1 + 4;
5526
+ const byteLength = (0, utf8_ts_1.utf8Count)(object);
5527
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
5528
+ this.writeStringHeader(byteLength);
5529
+ (0, utf8_ts_1.utf8Encode)(object, this.bytes, this.pos);
5530
+ this.pos += byteLength;
5531
+ }
5532
+ encodeObject(object, depth) {
5533
+ const ext = this.extensionCodec.tryToEncode(object, this.context);
5534
+ if (ext != null) {
5535
+ this.encodeExtension(ext);
5536
+ } else if (Array.isArray(object)) {
5537
+ this.encodeArray(object, depth);
5538
+ } else if (ArrayBuffer.isView(object)) {
5539
+ this.encodeBinary(object);
5540
+ } else if (typeof object === "object") {
5541
+ this.encodeMap(object, depth);
5542
+ } else {
5543
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
5544
+ }
5545
+ }
5546
+ encodeBinary(object) {
5547
+ const size2 = object.byteLength;
5548
+ if (size2 < 256) {
5549
+ this.writeU8(196);
5550
+ this.writeU8(size2);
5551
+ } else if (size2 < 65536) {
5552
+ this.writeU8(197);
5553
+ this.writeU16(size2);
5554
+ } else if (size2 < 4294967296) {
5555
+ this.writeU8(198);
5556
+ this.writeU32(size2);
5557
+ } else {
5558
+ throw new Error(`Too large binary: ${size2}`);
5559
+ }
5560
+ const bytes = (0, typedArrays_ts_1.ensureUint8Array)(object);
5561
+ this.writeU8a(bytes);
5562
+ }
5563
+ encodeArray(object, depth) {
5564
+ const size2 = object.length;
5565
+ if (size2 < 16) {
5566
+ this.writeU8(144 + size2);
5567
+ } else if (size2 < 65536) {
5568
+ this.writeU8(220);
5569
+ this.writeU16(size2);
5570
+ } else if (size2 < 4294967296) {
5571
+ this.writeU8(221);
5572
+ this.writeU32(size2);
5573
+ } else {
5574
+ throw new Error(`Too large array: ${size2}`);
5575
+ }
5576
+ for (const item of object) {
5577
+ this.doEncode(item, depth + 1);
5578
+ }
5579
+ }
5580
+ countWithoutUndefined(object, keys) {
5581
+ let count = 0;
5582
+ for (const key of keys) {
5583
+ if (object[key] !== void 0) {
5584
+ count++;
5585
+ }
5586
+ }
5587
+ return count;
5588
+ }
5589
+ encodeMap(object, depth) {
5590
+ const keys = Object.keys(object);
5591
+ if (this.sortKeys) {
5592
+ keys.sort();
5593
+ }
5594
+ const size2 = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
5595
+ if (size2 < 16) {
5596
+ this.writeU8(128 + size2);
5597
+ } else if (size2 < 65536) {
5598
+ this.writeU8(222);
5599
+ this.writeU16(size2);
5600
+ } else if (size2 < 4294967296) {
5601
+ this.writeU8(223);
5602
+ this.writeU32(size2);
5603
+ } else {
5604
+ throw new Error(`Too large map object: ${size2}`);
5605
+ }
5606
+ for (const key of keys) {
5607
+ const value = object[key];
5608
+ if (!(this.ignoreUndefined && value === void 0)) {
5609
+ this.encodeString(key);
5610
+ this.doEncode(value, depth + 1);
5611
+ }
5612
+ }
5613
+ }
5614
+ encodeExtension(ext) {
5615
+ if (typeof ext.data === "function") {
5616
+ const data = ext.data(this.pos + 6);
5617
+ const size3 = data.length;
5618
+ if (size3 >= 4294967296) {
5619
+ throw new Error(`Too large extension object: ${size3}`);
5620
+ }
5621
+ this.writeU8(201);
5622
+ this.writeU32(size3);
5623
+ this.writeI8(ext.type);
5624
+ this.writeU8a(data);
5625
+ return;
5626
+ }
5627
+ const size2 = ext.data.length;
5628
+ if (size2 === 1) {
5629
+ this.writeU8(212);
5630
+ } else if (size2 === 2) {
5631
+ this.writeU8(213);
5632
+ } else if (size2 === 4) {
5633
+ this.writeU8(214);
5634
+ } else if (size2 === 8) {
5635
+ this.writeU8(215);
5636
+ } else if (size2 === 16) {
5637
+ this.writeU8(216);
5638
+ } else if (size2 < 256) {
5639
+ this.writeU8(199);
5640
+ this.writeU8(size2);
5641
+ } else if (size2 < 65536) {
5642
+ this.writeU8(200);
5643
+ this.writeU16(size2);
5644
+ } else if (size2 < 4294967296) {
5645
+ this.writeU8(201);
5646
+ this.writeU32(size2);
5647
+ } else {
5648
+ throw new Error(`Too large extension object: ${size2}`);
5649
+ }
5650
+ this.writeI8(ext.type);
5651
+ this.writeU8a(ext.data);
5652
+ }
5653
+ writeU8(value) {
5654
+ this.ensureBufferSizeToWrite(1);
5655
+ this.view.setUint8(this.pos, value);
5656
+ this.pos++;
5657
+ }
5658
+ writeU8a(values) {
5659
+ const size2 = values.length;
5660
+ this.ensureBufferSizeToWrite(size2);
5661
+ this.bytes.set(values, this.pos);
5662
+ this.pos += size2;
5663
+ }
5664
+ writeI8(value) {
5665
+ this.ensureBufferSizeToWrite(1);
5666
+ this.view.setInt8(this.pos, value);
5667
+ this.pos++;
5668
+ }
5669
+ writeU16(value) {
5670
+ this.ensureBufferSizeToWrite(2);
5671
+ this.view.setUint16(this.pos, value);
5672
+ this.pos += 2;
5673
+ }
5674
+ writeI16(value) {
5675
+ this.ensureBufferSizeToWrite(2);
5676
+ this.view.setInt16(this.pos, value);
5677
+ this.pos += 2;
5678
+ }
5679
+ writeU32(value) {
5680
+ this.ensureBufferSizeToWrite(4);
5681
+ this.view.setUint32(this.pos, value);
5682
+ this.pos += 4;
5683
+ }
5684
+ writeI32(value) {
5685
+ this.ensureBufferSizeToWrite(4);
5686
+ this.view.setInt32(this.pos, value);
5687
+ this.pos += 4;
5688
+ }
5689
+ writeF32(value) {
5690
+ this.ensureBufferSizeToWrite(4);
5691
+ this.view.setFloat32(this.pos, value);
5692
+ this.pos += 4;
5693
+ }
5694
+ writeF64(value) {
5695
+ this.ensureBufferSizeToWrite(8);
5696
+ this.view.setFloat64(this.pos, value);
5697
+ this.pos += 8;
5698
+ }
5699
+ writeU64(value) {
5700
+ this.ensureBufferSizeToWrite(8);
5701
+ (0, int_ts_1.setUint64)(this.view, this.pos, value);
5702
+ this.pos += 8;
5703
+ }
5704
+ writeI64(value) {
5705
+ this.ensureBufferSizeToWrite(8);
5706
+ (0, int_ts_1.setInt64)(this.view, this.pos, value);
5707
+ this.pos += 8;
5708
+ }
5709
+ writeBigUint64(value) {
5710
+ this.ensureBufferSizeToWrite(8);
5711
+ this.view.setBigUint64(this.pos, value);
5712
+ this.pos += 8;
5713
+ }
5714
+ writeBigInt64(value) {
5715
+ this.ensureBufferSizeToWrite(8);
5716
+ this.view.setBigInt64(this.pos, value);
5717
+ this.pos += 8;
5718
+ }
5719
+ };
5720
+ exports.Encoder = Encoder;
5721
+ }
5722
+ });
5723
+
5724
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/encode.cjs
5725
+ var require_encode = __commonJS({
5726
+ "../../node_modules/@msgpack/msgpack/dist.cjs/encode.cjs"(exports) {
5727
+ "use strict";
5728
+ Object.defineProperty(exports, "__esModule", { value: true });
5729
+ exports.encode = encode;
5730
+ var Encoder_ts_1 = require_Encoder();
5731
+ function encode(value, options) {
5732
+ const encoder3 = new Encoder_ts_1.Encoder(options);
5733
+ return encoder3.encodeSharedRef(value);
5734
+ }
5735
+ }
5736
+ });
5737
+
5738
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/utils/prettyByte.cjs
5739
+ var require_prettyByte = __commonJS({
5740
+ "../../node_modules/@msgpack/msgpack/dist.cjs/utils/prettyByte.cjs"(exports) {
5741
+ "use strict";
5742
+ Object.defineProperty(exports, "__esModule", { value: true });
5743
+ exports.prettyByte = prettyByte;
5744
+ function prettyByte(byte) {
5745
+ return `${byte < 0 ? "-" : ""}0x${Math.abs(byte).toString(16).padStart(2, "0")}`;
5746
+ }
5747
+ }
5748
+ });
5749
+
5750
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/CachedKeyDecoder.cjs
5751
+ var require_CachedKeyDecoder = __commonJS({
5752
+ "../../node_modules/@msgpack/msgpack/dist.cjs/CachedKeyDecoder.cjs"(exports) {
5753
+ "use strict";
5754
+ Object.defineProperty(exports, "__esModule", { value: true });
5755
+ exports.CachedKeyDecoder = void 0;
5756
+ var utf8_ts_1 = require_utf8();
5757
+ var DEFAULT_MAX_KEY_LENGTH = 16;
5758
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
5759
+ var CachedKeyDecoder = class {
5760
+ hit = 0;
5761
+ miss = 0;
5762
+ caches;
5763
+ maxKeyLength;
5764
+ maxLengthPerKey;
5765
+ constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
5766
+ this.maxKeyLength = maxKeyLength;
5767
+ this.maxLengthPerKey = maxLengthPerKey;
5768
+ this.caches = [];
5769
+ for (let i = 0; i < this.maxKeyLength; i++) {
5770
+ this.caches.push([]);
5771
+ }
5772
+ }
5773
+ canBeCached(byteLength) {
5774
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
5775
+ }
5776
+ find(bytes, inputOffset, byteLength) {
5777
+ const records = this.caches[byteLength - 1];
5778
+ FIND_CHUNK: for (const record of records) {
5779
+ const recordBytes = record.bytes;
5780
+ for (let j = 0; j < byteLength; j++) {
5781
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
5782
+ continue FIND_CHUNK;
5783
+ }
5784
+ }
5785
+ return record.str;
5786
+ }
5787
+ return null;
5788
+ }
5789
+ store(bytes, value) {
5790
+ const records = this.caches[bytes.length - 1];
5791
+ const record = { bytes, str: value };
5792
+ if (records.length >= this.maxLengthPerKey) {
5793
+ records[Math.random() * records.length | 0] = record;
5794
+ } else {
5795
+ records.push(record);
5796
+ }
5797
+ }
5798
+ decode(bytes, inputOffset, byteLength) {
5799
+ const cachedValue = this.find(bytes, inputOffset, byteLength);
5800
+ if (cachedValue != null) {
5801
+ this.hit++;
5802
+ return cachedValue;
5803
+ }
5804
+ this.miss++;
5805
+ const str2 = (0, utf8_ts_1.utf8DecodeJs)(bytes, inputOffset, byteLength);
5806
+ const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
5807
+ this.store(slicedCopyOfBytes, str2);
5808
+ return str2;
5809
+ }
5810
+ };
5811
+ exports.CachedKeyDecoder = CachedKeyDecoder;
5812
+ }
5813
+ });
5814
+
5815
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/Decoder.cjs
5816
+ var require_Decoder = __commonJS({
5817
+ "../../node_modules/@msgpack/msgpack/dist.cjs/Decoder.cjs"(exports) {
5818
+ "use strict";
5819
+ Object.defineProperty(exports, "__esModule", { value: true });
5820
+ exports.Decoder = void 0;
5821
+ var prettyByte_ts_1 = require_prettyByte();
5822
+ var ExtensionCodec_ts_1 = require_ExtensionCodec();
5823
+ var int_ts_1 = require_int();
5824
+ var utf8_ts_1 = require_utf8();
5825
+ var typedArrays_ts_1 = require_typedArrays();
5826
+ var CachedKeyDecoder_ts_1 = require_CachedKeyDecoder();
5827
+ var DecodeError_ts_1 = require_DecodeError();
5828
+ var STATE_ARRAY = "array";
5829
+ var STATE_MAP_KEY = "map_key";
5830
+ var STATE_MAP_VALUE = "map_value";
5831
+ var mapKeyConverter = (key) => {
5832
+ if (typeof key === "string" || typeof key === "number") {
5833
+ return key;
5834
+ }
5835
+ throw new DecodeError_ts_1.DecodeError("The type of key must be string or number but " + typeof key);
5836
+ };
5837
+ var StackPool = class {
5838
+ stack = [];
5839
+ stackHeadPosition = -1;
5840
+ get length() {
5841
+ return this.stackHeadPosition + 1;
5842
+ }
5843
+ top() {
5844
+ return this.stack[this.stackHeadPosition];
5845
+ }
5846
+ pushArrayState(size2) {
5847
+ const state = this.getUninitializedStateFromPool();
5848
+ state.type = STATE_ARRAY;
5849
+ state.position = 0;
5850
+ state.size = size2;
5851
+ state.array = new Array(size2);
5852
+ }
5853
+ pushMapState(size2) {
5854
+ const state = this.getUninitializedStateFromPool();
5855
+ state.type = STATE_MAP_KEY;
5856
+ state.readCount = 0;
5857
+ state.size = size2;
5858
+ state.map = {};
5859
+ }
5860
+ getUninitializedStateFromPool() {
5861
+ this.stackHeadPosition++;
5862
+ if (this.stackHeadPosition === this.stack.length) {
5863
+ const partialState = {
5864
+ type: void 0,
5865
+ size: 0,
5866
+ array: void 0,
5867
+ position: 0,
5868
+ readCount: 0,
5869
+ map: void 0,
5870
+ key: null
5871
+ };
5872
+ this.stack.push(partialState);
5873
+ }
5874
+ return this.stack[this.stackHeadPosition];
5875
+ }
5876
+ release(state) {
5877
+ const topStackState = this.stack[this.stackHeadPosition];
5878
+ if (topStackState !== state) {
5879
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
5880
+ }
5881
+ if (state.type === STATE_ARRAY) {
5882
+ const partialState = state;
5883
+ partialState.size = 0;
5884
+ partialState.array = void 0;
5885
+ partialState.position = 0;
5886
+ partialState.type = void 0;
5887
+ }
5888
+ if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {
5889
+ const partialState = state;
5890
+ partialState.size = 0;
5891
+ partialState.map = void 0;
5892
+ partialState.readCount = 0;
5893
+ partialState.type = void 0;
5894
+ }
5895
+ this.stackHeadPosition--;
5896
+ }
5897
+ reset() {
5898
+ this.stack.length = 0;
5899
+ this.stackHeadPosition = -1;
5900
+ }
5901
+ };
5902
+ var HEAD_BYTE_REQUIRED = -1;
5903
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
5904
+ var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
5905
+ try {
5906
+ EMPTY_VIEW.getInt8(0);
5907
+ } catch (e) {
5908
+ if (!(e instanceof RangeError)) {
5909
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
5910
+ }
5911
+ }
5912
+ var MORE_DATA = new RangeError("Insufficient data");
5913
+ var sharedCachedKeyDecoder = new CachedKeyDecoder_ts_1.CachedKeyDecoder();
5914
+ var Decoder = class _Decoder {
5915
+ extensionCodec;
5916
+ context;
5917
+ useBigInt64;
5918
+ rawStrings;
5919
+ maxStrLength;
5920
+ maxBinLength;
5921
+ maxArrayLength;
5922
+ maxMapLength;
5923
+ maxExtLength;
5924
+ keyDecoder;
5925
+ mapKeyConverter;
5926
+ totalPos = 0;
5927
+ pos = 0;
5928
+ view = EMPTY_VIEW;
5929
+ bytes = EMPTY_BYTES;
5930
+ headByte = HEAD_BYTE_REQUIRED;
5931
+ stack = new StackPool();
5932
+ entered = false;
5933
+ constructor(options) {
5934
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec_ts_1.ExtensionCodec.defaultCodec;
5935
+ this.context = options?.context;
5936
+ this.useBigInt64 = options?.useBigInt64 ?? false;
5937
+ this.rawStrings = options?.rawStrings ?? false;
5938
+ this.maxStrLength = options?.maxStrLength ?? int_ts_1.UINT32_MAX;
5939
+ this.maxBinLength = options?.maxBinLength ?? int_ts_1.UINT32_MAX;
5940
+ this.maxArrayLength = options?.maxArrayLength ?? int_ts_1.UINT32_MAX;
5941
+ this.maxMapLength = options?.maxMapLength ?? int_ts_1.UINT32_MAX;
5942
+ this.maxExtLength = options?.maxExtLength ?? int_ts_1.UINT32_MAX;
5943
+ this.keyDecoder = options?.keyDecoder !== void 0 ? options.keyDecoder : sharedCachedKeyDecoder;
5944
+ this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;
5945
+ }
5946
+ clone() {
5947
+ return new _Decoder({
5948
+ extensionCodec: this.extensionCodec,
5949
+ context: this.context,
5950
+ useBigInt64: this.useBigInt64,
5951
+ rawStrings: this.rawStrings,
5952
+ maxStrLength: this.maxStrLength,
5953
+ maxBinLength: this.maxBinLength,
5954
+ maxArrayLength: this.maxArrayLength,
5955
+ maxMapLength: this.maxMapLength,
5956
+ maxExtLength: this.maxExtLength,
5957
+ keyDecoder: this.keyDecoder
5958
+ });
5959
+ }
5960
+ reinitializeState() {
5961
+ this.totalPos = 0;
5962
+ this.headByte = HEAD_BYTE_REQUIRED;
5963
+ this.stack.reset();
5964
+ }
5965
+ setBuffer(buffer) {
5966
+ const bytes = (0, typedArrays_ts_1.ensureUint8Array)(buffer);
5967
+ this.bytes = bytes;
5968
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5969
+ this.pos = 0;
5970
+ }
5971
+ appendBuffer(buffer) {
5972
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
5973
+ this.setBuffer(buffer);
5974
+ } else {
5975
+ const remainingData = this.bytes.subarray(this.pos);
5976
+ const newData = (0, typedArrays_ts_1.ensureUint8Array)(buffer);
5977
+ const newBuffer = new Uint8Array(remainingData.length + newData.length);
5978
+ newBuffer.set(remainingData);
5979
+ newBuffer.set(newData, remainingData.length);
5980
+ this.setBuffer(newBuffer);
5981
+ }
5982
+ }
5983
+ hasRemaining(size2) {
5984
+ return this.view.byteLength - this.pos >= size2;
5985
+ }
5986
+ createExtraByteError(posToShow) {
5987
+ const { view, pos } = this;
5988
+ return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);
5989
+ }
5990
+ /**
5991
+ * @throws {@link DecodeError}
5992
+ * @throws {@link RangeError}
5993
+ */
5994
+ decode(buffer) {
5995
+ if (this.entered) {
5996
+ const instance = this.clone();
5997
+ return instance.decode(buffer);
5998
+ }
5999
+ try {
6000
+ this.entered = true;
6001
+ this.reinitializeState();
6002
+ this.setBuffer(buffer);
6003
+ const object = this.doDecodeSync();
6004
+ if (this.hasRemaining(1)) {
6005
+ throw this.createExtraByteError(this.pos);
6006
+ }
6007
+ return object;
6008
+ } finally {
6009
+ this.entered = false;
6010
+ }
6011
+ }
6012
+ *decodeMulti(buffer) {
6013
+ if (this.entered) {
6014
+ const instance = this.clone();
6015
+ yield* instance.decodeMulti(buffer);
6016
+ return;
6017
+ }
6018
+ try {
6019
+ this.entered = true;
6020
+ this.reinitializeState();
6021
+ this.setBuffer(buffer);
6022
+ while (this.hasRemaining(1)) {
6023
+ yield this.doDecodeSync();
6024
+ }
6025
+ } finally {
6026
+ this.entered = false;
6027
+ }
6028
+ }
6029
+ async decodeAsync(stream) {
6030
+ if (this.entered) {
6031
+ const instance = this.clone();
6032
+ return instance.decodeAsync(stream);
6033
+ }
6034
+ try {
6035
+ this.entered = true;
6036
+ let decoded = false;
6037
+ let object;
6038
+ for await (const buffer of stream) {
6039
+ if (decoded) {
6040
+ this.entered = false;
6041
+ throw this.createExtraByteError(this.totalPos);
6042
+ }
6043
+ this.appendBuffer(buffer);
6044
+ try {
6045
+ object = this.doDecodeSync();
6046
+ decoded = true;
6047
+ } catch (e) {
6048
+ if (!(e instanceof RangeError)) {
6049
+ throw e;
6050
+ }
6051
+ }
6052
+ this.totalPos += this.pos;
6053
+ }
6054
+ if (decoded) {
6055
+ if (this.hasRemaining(1)) {
6056
+ throw this.createExtraByteError(this.totalPos);
6057
+ }
6058
+ return object;
6059
+ }
6060
+ const { headByte, pos, totalPos } = this;
6061
+ throw new RangeError(`Insufficient data in parsing ${(0, prettyByte_ts_1.prettyByte)(headByte)} at ${totalPos} (${pos} in the current buffer)`);
6062
+ } finally {
6063
+ this.entered = false;
6064
+ }
6065
+ }
6066
+ decodeArrayStream(stream) {
6067
+ return this.decodeMultiAsync(stream, true);
6068
+ }
6069
+ decodeStream(stream) {
6070
+ return this.decodeMultiAsync(stream, false);
6071
+ }
6072
+ async *decodeMultiAsync(stream, isArray) {
6073
+ if (this.entered) {
6074
+ const instance = this.clone();
6075
+ yield* instance.decodeMultiAsync(stream, isArray);
6076
+ return;
6077
+ }
6078
+ try {
6079
+ this.entered = true;
6080
+ let isArrayHeaderRequired = isArray;
6081
+ let arrayItemsLeft = -1;
6082
+ for await (const buffer of stream) {
6083
+ if (isArray && arrayItemsLeft === 0) {
6084
+ throw this.createExtraByteError(this.totalPos);
6085
+ }
6086
+ this.appendBuffer(buffer);
6087
+ if (isArrayHeaderRequired) {
6088
+ arrayItemsLeft = this.readArraySize();
6089
+ isArrayHeaderRequired = false;
6090
+ this.complete();
6091
+ }
6092
+ try {
6093
+ while (true) {
6094
+ yield this.doDecodeSync();
6095
+ if (--arrayItemsLeft === 0) {
6096
+ break;
6097
+ }
6098
+ }
6099
+ } catch (e) {
6100
+ if (!(e instanceof RangeError)) {
6101
+ throw e;
6102
+ }
6103
+ }
6104
+ this.totalPos += this.pos;
6105
+ }
6106
+ } finally {
6107
+ this.entered = false;
6108
+ }
6109
+ }
6110
+ doDecodeSync() {
6111
+ DECODE: while (true) {
6112
+ const headByte = this.readHeadByte();
6113
+ let object;
6114
+ if (headByte >= 224) {
6115
+ object = headByte - 256;
6116
+ } else if (headByte < 192) {
6117
+ if (headByte < 128) {
6118
+ object = headByte;
6119
+ } else if (headByte < 144) {
6120
+ const size2 = headByte - 128;
6121
+ if (size2 !== 0) {
6122
+ this.pushMapState(size2);
6123
+ this.complete();
6124
+ continue DECODE;
6125
+ } else {
6126
+ object = {};
6127
+ }
6128
+ } else if (headByte < 160) {
6129
+ const size2 = headByte - 144;
6130
+ if (size2 !== 0) {
6131
+ this.pushArrayState(size2);
6132
+ this.complete();
6133
+ continue DECODE;
6134
+ } else {
6135
+ object = [];
6136
+ }
6137
+ } else {
6138
+ const byteLength = headByte - 160;
6139
+ object = this.decodeString(byteLength, 0);
6140
+ }
6141
+ } else if (headByte === 192) {
6142
+ object = null;
6143
+ } else if (headByte === 194) {
6144
+ object = false;
6145
+ } else if (headByte === 195) {
6146
+ object = true;
6147
+ } else if (headByte === 202) {
6148
+ object = this.readF32();
6149
+ } else if (headByte === 203) {
6150
+ object = this.readF64();
6151
+ } else if (headByte === 204) {
6152
+ object = this.readU8();
6153
+ } else if (headByte === 205) {
6154
+ object = this.readU16();
6155
+ } else if (headByte === 206) {
6156
+ object = this.readU32();
6157
+ } else if (headByte === 207) {
6158
+ if (this.useBigInt64) {
6159
+ object = this.readU64AsBigInt();
6160
+ } else {
6161
+ object = this.readU64();
6162
+ }
6163
+ } else if (headByte === 208) {
6164
+ object = this.readI8();
6165
+ } else if (headByte === 209) {
6166
+ object = this.readI16();
6167
+ } else if (headByte === 210) {
6168
+ object = this.readI32();
6169
+ } else if (headByte === 211) {
6170
+ if (this.useBigInt64) {
6171
+ object = this.readI64AsBigInt();
6172
+ } else {
6173
+ object = this.readI64();
6174
+ }
6175
+ } else if (headByte === 217) {
6176
+ const byteLength = this.lookU8();
6177
+ object = this.decodeString(byteLength, 1);
6178
+ } else if (headByte === 218) {
6179
+ const byteLength = this.lookU16();
6180
+ object = this.decodeString(byteLength, 2);
6181
+ } else if (headByte === 219) {
6182
+ const byteLength = this.lookU32();
6183
+ object = this.decodeString(byteLength, 4);
6184
+ } else if (headByte === 220) {
6185
+ const size2 = this.readU16();
6186
+ if (size2 !== 0) {
6187
+ this.pushArrayState(size2);
6188
+ this.complete();
6189
+ continue DECODE;
6190
+ } else {
6191
+ object = [];
6192
+ }
6193
+ } else if (headByte === 221) {
6194
+ const size2 = this.readU32();
6195
+ if (size2 !== 0) {
6196
+ this.pushArrayState(size2);
6197
+ this.complete();
6198
+ continue DECODE;
6199
+ } else {
6200
+ object = [];
6201
+ }
6202
+ } else if (headByte === 222) {
6203
+ const size2 = this.readU16();
6204
+ if (size2 !== 0) {
6205
+ this.pushMapState(size2);
6206
+ this.complete();
6207
+ continue DECODE;
6208
+ } else {
6209
+ object = {};
6210
+ }
6211
+ } else if (headByte === 223) {
6212
+ const size2 = this.readU32();
6213
+ if (size2 !== 0) {
6214
+ this.pushMapState(size2);
6215
+ this.complete();
6216
+ continue DECODE;
6217
+ } else {
6218
+ object = {};
6219
+ }
6220
+ } else if (headByte === 196) {
6221
+ const size2 = this.lookU8();
6222
+ object = this.decodeBinary(size2, 1);
6223
+ } else if (headByte === 197) {
6224
+ const size2 = this.lookU16();
6225
+ object = this.decodeBinary(size2, 2);
6226
+ } else if (headByte === 198) {
6227
+ const size2 = this.lookU32();
6228
+ object = this.decodeBinary(size2, 4);
6229
+ } else if (headByte === 212) {
6230
+ object = this.decodeExtension(1, 0);
6231
+ } else if (headByte === 213) {
6232
+ object = this.decodeExtension(2, 0);
6233
+ } else if (headByte === 214) {
6234
+ object = this.decodeExtension(4, 0);
6235
+ } else if (headByte === 215) {
6236
+ object = this.decodeExtension(8, 0);
6237
+ } else if (headByte === 216) {
6238
+ object = this.decodeExtension(16, 0);
6239
+ } else if (headByte === 199) {
6240
+ const size2 = this.lookU8();
6241
+ object = this.decodeExtension(size2, 1);
6242
+ } else if (headByte === 200) {
6243
+ const size2 = this.lookU16();
6244
+ object = this.decodeExtension(size2, 2);
6245
+ } else if (headByte === 201) {
6246
+ const size2 = this.lookU32();
6247
+ object = this.decodeExtension(size2, 4);
6248
+ } else {
6249
+ throw new DecodeError_ts_1.DecodeError(`Unrecognized type byte: ${(0, prettyByte_ts_1.prettyByte)(headByte)}`);
6250
+ }
6251
+ this.complete();
6252
+ const stack = this.stack;
6253
+ while (stack.length > 0) {
6254
+ const state = stack.top();
6255
+ if (state.type === STATE_ARRAY) {
6256
+ state.array[state.position] = object;
6257
+ state.position++;
6258
+ if (state.position === state.size) {
6259
+ object = state.array;
6260
+ stack.release(state);
6261
+ } else {
6262
+ continue DECODE;
6263
+ }
6264
+ } else if (state.type === STATE_MAP_KEY) {
6265
+ if (object === "__proto__") {
6266
+ throw new DecodeError_ts_1.DecodeError("The key __proto__ is not allowed");
6267
+ }
6268
+ state.key = this.mapKeyConverter(object);
6269
+ state.type = STATE_MAP_VALUE;
6270
+ continue DECODE;
6271
+ } else {
6272
+ state.map[state.key] = object;
6273
+ state.readCount++;
6274
+ if (state.readCount === state.size) {
6275
+ object = state.map;
6276
+ stack.release(state);
6277
+ } else {
6278
+ state.key = null;
6279
+ state.type = STATE_MAP_KEY;
6280
+ continue DECODE;
6281
+ }
6282
+ }
6283
+ }
6284
+ return object;
6285
+ }
6286
+ }
6287
+ readHeadByte() {
6288
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
6289
+ this.headByte = this.readU8();
6290
+ }
6291
+ return this.headByte;
6292
+ }
6293
+ complete() {
6294
+ this.headByte = HEAD_BYTE_REQUIRED;
6295
+ }
6296
+ readArraySize() {
6297
+ const headByte = this.readHeadByte();
6298
+ switch (headByte) {
6299
+ case 220:
6300
+ return this.readU16();
6301
+ case 221:
6302
+ return this.readU32();
6303
+ default: {
6304
+ if (headByte < 160) {
6305
+ return headByte - 144;
6306
+ } else {
6307
+ throw new DecodeError_ts_1.DecodeError(`Unrecognized array type byte: ${(0, prettyByte_ts_1.prettyByte)(headByte)}`);
6308
+ }
6309
+ }
6310
+ }
6311
+ }
6312
+ pushMapState(size2) {
6313
+ if (size2 > this.maxMapLength) {
6314
+ throw new DecodeError_ts_1.DecodeError(`Max length exceeded: map length (${size2}) > maxMapLengthLength (${this.maxMapLength})`);
6315
+ }
6316
+ this.stack.pushMapState(size2);
6317
+ }
6318
+ pushArrayState(size2) {
6319
+ if (size2 > this.maxArrayLength) {
6320
+ throw new DecodeError_ts_1.DecodeError(`Max length exceeded: array length (${size2}) > maxArrayLength (${this.maxArrayLength})`);
6321
+ }
6322
+ this.stack.pushArrayState(size2);
6323
+ }
6324
+ decodeString(byteLength, headerOffset) {
6325
+ if (!this.rawStrings || this.stateIsMapKey()) {
6326
+ return this.decodeUtf8String(byteLength, headerOffset);
6327
+ }
6328
+ return this.decodeBinary(byteLength, headerOffset);
6329
+ }
6330
+ /**
6331
+ * @throws {@link RangeError}
6332
+ */
6333
+ decodeUtf8String(byteLength, headerOffset) {
6334
+ if (byteLength > this.maxStrLength) {
6335
+ throw new DecodeError_ts_1.DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);
6336
+ }
6337
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
6338
+ throw MORE_DATA;
6339
+ }
6340
+ const offset = this.pos + headerOffset;
6341
+ let object;
6342
+ if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {
6343
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
6344
+ } else {
6345
+ object = (0, utf8_ts_1.utf8Decode)(this.bytes, offset, byteLength);
6346
+ }
6347
+ this.pos += headerOffset + byteLength;
6348
+ return object;
6349
+ }
6350
+ stateIsMapKey() {
6351
+ if (this.stack.length > 0) {
6352
+ const state = this.stack.top();
6353
+ return state.type === STATE_MAP_KEY;
6354
+ }
6355
+ return false;
6356
+ }
6357
+ /**
6358
+ * @throws {@link RangeError}
6359
+ */
6360
+ decodeBinary(byteLength, headOffset) {
6361
+ if (byteLength > this.maxBinLength) {
6362
+ throw new DecodeError_ts_1.DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);
6363
+ }
6364
+ if (!this.hasRemaining(byteLength + headOffset)) {
6365
+ throw MORE_DATA;
6366
+ }
6367
+ const offset = this.pos + headOffset;
6368
+ const object = this.bytes.subarray(offset, offset + byteLength);
6369
+ this.pos += headOffset + byteLength;
6370
+ return object;
6371
+ }
6372
+ decodeExtension(size2, headOffset) {
6373
+ if (size2 > this.maxExtLength) {
6374
+ throw new DecodeError_ts_1.DecodeError(`Max length exceeded: ext length (${size2}) > maxExtLength (${this.maxExtLength})`);
6375
+ }
6376
+ const extType = this.view.getInt8(this.pos + headOffset);
6377
+ const data = this.decodeBinary(
6378
+ size2,
6379
+ headOffset + 1
6380
+ /* extType */
6381
+ );
6382
+ return this.extensionCodec.decode(data, extType, this.context);
6383
+ }
6384
+ lookU8() {
6385
+ return this.view.getUint8(this.pos);
6386
+ }
6387
+ lookU16() {
6388
+ return this.view.getUint16(this.pos);
6389
+ }
6390
+ lookU32() {
6391
+ return this.view.getUint32(this.pos);
6392
+ }
6393
+ readU8() {
6394
+ const value = this.view.getUint8(this.pos);
6395
+ this.pos++;
6396
+ return value;
6397
+ }
6398
+ readI8() {
6399
+ const value = this.view.getInt8(this.pos);
6400
+ this.pos++;
6401
+ return value;
6402
+ }
6403
+ readU16() {
6404
+ const value = this.view.getUint16(this.pos);
6405
+ this.pos += 2;
6406
+ return value;
6407
+ }
6408
+ readI16() {
6409
+ const value = this.view.getInt16(this.pos);
6410
+ this.pos += 2;
6411
+ return value;
6412
+ }
6413
+ readU32() {
6414
+ const value = this.view.getUint32(this.pos);
6415
+ this.pos += 4;
6416
+ return value;
6417
+ }
6418
+ readI32() {
6419
+ const value = this.view.getInt32(this.pos);
6420
+ this.pos += 4;
6421
+ return value;
6422
+ }
6423
+ readU64() {
6424
+ const value = (0, int_ts_1.getUint64)(this.view, this.pos);
6425
+ this.pos += 8;
6426
+ return value;
6427
+ }
6428
+ readI64() {
6429
+ const value = (0, int_ts_1.getInt64)(this.view, this.pos);
6430
+ this.pos += 8;
6431
+ return value;
6432
+ }
6433
+ readU64AsBigInt() {
6434
+ const value = this.view.getBigUint64(this.pos);
6435
+ this.pos += 8;
6436
+ return value;
6437
+ }
6438
+ readI64AsBigInt() {
6439
+ const value = this.view.getBigInt64(this.pos);
6440
+ this.pos += 8;
6441
+ return value;
6442
+ }
6443
+ readF32() {
6444
+ const value = this.view.getFloat32(this.pos);
6445
+ this.pos += 4;
6446
+ return value;
6447
+ }
6448
+ readF64() {
6449
+ const value = this.view.getFloat64(this.pos);
6450
+ this.pos += 8;
6451
+ return value;
6452
+ }
6453
+ };
6454
+ exports.Decoder = Decoder;
6455
+ }
6456
+ });
6457
+
6458
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/decode.cjs
6459
+ var require_decode = __commonJS({
6460
+ "../../node_modules/@msgpack/msgpack/dist.cjs/decode.cjs"(exports) {
6461
+ "use strict";
6462
+ Object.defineProperty(exports, "__esModule", { value: true });
6463
+ exports.decode = decode;
6464
+ exports.decodeMulti = decodeMulti;
6465
+ var Decoder_ts_1 = require_Decoder();
6466
+ function decode(buffer, options) {
6467
+ const decoder = new Decoder_ts_1.Decoder(options);
6468
+ return decoder.decode(buffer);
6469
+ }
6470
+ function decodeMulti(buffer, options) {
6471
+ const decoder = new Decoder_ts_1.Decoder(options);
6472
+ return decoder.decodeMulti(buffer);
6473
+ }
6474
+ }
6475
+ });
6476
+
6477
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/utils/stream.cjs
6478
+ var require_stream = __commonJS({
6479
+ "../../node_modules/@msgpack/msgpack/dist.cjs/utils/stream.cjs"(exports) {
6480
+ "use strict";
6481
+ Object.defineProperty(exports, "__esModule", { value: true });
6482
+ exports.isAsyncIterable = isAsyncIterable;
6483
+ exports.asyncIterableFromStream = asyncIterableFromStream;
6484
+ exports.ensureAsyncIterable = ensureAsyncIterable;
6485
+ function isAsyncIterable(object) {
6486
+ return object[Symbol.asyncIterator] != null;
6487
+ }
6488
+ async function* asyncIterableFromStream(stream) {
6489
+ const reader = stream.getReader();
6490
+ try {
6491
+ while (true) {
6492
+ const { done, value } = await reader.read();
6493
+ if (done) {
6494
+ return;
6495
+ }
6496
+ yield value;
4376
6497
  }
6498
+ } finally {
6499
+ reader.releaseLock();
4377
6500
  }
4378
- }, sha256);
4379
- TAGGED_HASH_PREFIXES = {};
4380
- pointToBytes = (point) => point.toRawBytes(true).slice(1);
4381
- numTo32b = (n) => numberToBytesBE(n, 32);
4382
- modP = (x) => mod(x, secp256k1P);
4383
- modN = (x) => mod(x, secp256k1N);
4384
- Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();
4385
- GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
4386
- num = bytesToNumberBE;
4387
- schnorr = /* @__PURE__ */ (() => ({
4388
- getPublicKey: schnorrGetPublicKey,
4389
- sign: schnorrSign,
4390
- verify: schnorrVerify,
4391
- utils: {
4392
- randomPrivateKey: secp256k1.utils.randomPrivateKey,
4393
- lift_x,
4394
- pointToBytes,
4395
- numberToBytesBE,
4396
- bytesToNumberBE,
4397
- taggedHash,
4398
- mod
6501
+ }
6502
+ function ensureAsyncIterable(streamLike) {
6503
+ if (isAsyncIterable(streamLike)) {
6504
+ return streamLike;
6505
+ } else {
6506
+ return asyncIterableFromStream(streamLike);
4399
6507
  }
4400
- }))();
4401
- isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
4402
- // xNum
4403
- [
4404
- "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
4405
- "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
4406
- "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
4407
- "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
4408
- ],
4409
- // xDen
4410
- [
4411
- "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
4412
- "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
4413
- "0x0000000000000000000000000000000000000000000000000000000000000001"
4414
- // LAST 1
4415
- ],
4416
- // yNum
4417
- [
4418
- "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
4419
- "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
4420
- "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
4421
- "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
4422
- ],
4423
- // yDen
4424
- [
4425
- "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
4426
- "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
4427
- "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
4428
- "0x0000000000000000000000000000000000000000000000000000000000000001"
4429
- // LAST 1
4430
- ]
4431
- ].map((i) => i.map((j) => BigInt(j)))))();
4432
- mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
4433
- A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
4434
- B: BigInt("1771"),
4435
- Z: Fpk1.create(BigInt("-11"))
4436
- }))();
4437
- secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => {
4438
- const { x, y } = mapSWU(Fpk1.create(scalars[0]));
4439
- return isoMap(x, y);
4440
- }, {
4441
- DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
4442
- encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
4443
- p: Fpk1.ORDER,
4444
- m: 1,
4445
- k: 128,
4446
- expand: "xmd",
4447
- hash: sha256
4448
- }))();
4449
- hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
4450
- encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
6508
+ }
6509
+ }
6510
+ });
6511
+
6512
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/decodeAsync.cjs
6513
+ var require_decodeAsync = __commonJS({
6514
+ "../../node_modules/@msgpack/msgpack/dist.cjs/decodeAsync.cjs"(exports) {
6515
+ "use strict";
6516
+ Object.defineProperty(exports, "__esModule", { value: true });
6517
+ exports.decodeAsync = decodeAsync;
6518
+ exports.decodeArrayStream = decodeArrayStream;
6519
+ exports.decodeMultiStream = decodeMultiStream;
6520
+ var Decoder_ts_1 = require_Decoder();
6521
+ var stream_ts_1 = require_stream();
6522
+ async function decodeAsync(streamLike, options) {
6523
+ const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);
6524
+ const decoder = new Decoder_ts_1.Decoder(options);
6525
+ return decoder.decodeAsync(stream);
6526
+ }
6527
+ function decodeArrayStream(streamLike, options) {
6528
+ const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);
6529
+ const decoder = new Decoder_ts_1.Decoder(options);
6530
+ return decoder.decodeArrayStream(stream);
6531
+ }
6532
+ function decodeMultiStream(streamLike, options) {
6533
+ const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);
6534
+ const decoder = new Decoder_ts_1.Decoder(options);
6535
+ return decoder.decodeStream(stream);
6536
+ }
6537
+ }
6538
+ });
6539
+
6540
+ // ../../node_modules/@msgpack/msgpack/dist.cjs/index.cjs
6541
+ var require_dist = __commonJS({
6542
+ "../../node_modules/@msgpack/msgpack/dist.cjs/index.cjs"(exports) {
6543
+ "use strict";
6544
+ Object.defineProperty(exports, "__esModule", { value: true });
6545
+ exports.decodeTimestampExtension = exports.encodeTimestampExtension = exports.decodeTimestampToTimeSpec = exports.encodeTimeSpecToTimestamp = exports.encodeDateToTimeSpec = exports.EXT_TIMESTAMP = exports.ExtData = exports.ExtensionCodec = exports.Encoder = exports.DecodeError = exports.Decoder = exports.decodeMultiStream = exports.decodeArrayStream = exports.decodeAsync = exports.decodeMulti = exports.decode = exports.encode = void 0;
6546
+ var encode_ts_1 = require_encode();
6547
+ Object.defineProperty(exports, "encode", { enumerable: true, get: function() {
6548
+ return encode_ts_1.encode;
6549
+ } });
6550
+ var decode_ts_1 = require_decode();
6551
+ Object.defineProperty(exports, "decode", { enumerable: true, get: function() {
6552
+ return decode_ts_1.decode;
6553
+ } });
6554
+ Object.defineProperty(exports, "decodeMulti", { enumerable: true, get: function() {
6555
+ return decode_ts_1.decodeMulti;
6556
+ } });
6557
+ var decodeAsync_ts_1 = require_decodeAsync();
6558
+ Object.defineProperty(exports, "decodeAsync", { enumerable: true, get: function() {
6559
+ return decodeAsync_ts_1.decodeAsync;
6560
+ } });
6561
+ Object.defineProperty(exports, "decodeArrayStream", { enumerable: true, get: function() {
6562
+ return decodeAsync_ts_1.decodeArrayStream;
6563
+ } });
6564
+ Object.defineProperty(exports, "decodeMultiStream", { enumerable: true, get: function() {
6565
+ return decodeAsync_ts_1.decodeMultiStream;
6566
+ } });
6567
+ var Decoder_ts_1 = require_Decoder();
6568
+ Object.defineProperty(exports, "Decoder", { enumerable: true, get: function() {
6569
+ return Decoder_ts_1.Decoder;
6570
+ } });
6571
+ var DecodeError_ts_1 = require_DecodeError();
6572
+ Object.defineProperty(exports, "DecodeError", { enumerable: true, get: function() {
6573
+ return DecodeError_ts_1.DecodeError;
6574
+ } });
6575
+ var Encoder_ts_1 = require_Encoder();
6576
+ Object.defineProperty(exports, "Encoder", { enumerable: true, get: function() {
6577
+ return Encoder_ts_1.Encoder;
6578
+ } });
6579
+ var ExtensionCodec_ts_1 = require_ExtensionCodec();
6580
+ Object.defineProperty(exports, "ExtensionCodec", { enumerable: true, get: function() {
6581
+ return ExtensionCodec_ts_1.ExtensionCodec;
6582
+ } });
6583
+ var ExtData_ts_1 = require_ExtData();
6584
+ Object.defineProperty(exports, "ExtData", { enumerable: true, get: function() {
6585
+ return ExtData_ts_1.ExtData;
6586
+ } });
6587
+ var timestamp_ts_1 = require_timestamp();
6588
+ Object.defineProperty(exports, "EXT_TIMESTAMP", { enumerable: true, get: function() {
6589
+ return timestamp_ts_1.EXT_TIMESTAMP;
6590
+ } });
6591
+ Object.defineProperty(exports, "encodeDateToTimeSpec", { enumerable: true, get: function() {
6592
+ return timestamp_ts_1.encodeDateToTimeSpec;
6593
+ } });
6594
+ Object.defineProperty(exports, "encodeTimeSpecToTimestamp", { enumerable: true, get: function() {
6595
+ return timestamp_ts_1.encodeTimeSpecToTimestamp;
6596
+ } });
6597
+ Object.defineProperty(exports, "decodeTimestampToTimeSpec", { enumerable: true, get: function() {
6598
+ return timestamp_ts_1.decodeTimestampToTimeSpec;
6599
+ } });
6600
+ Object.defineProperty(exports, "encodeTimestampExtension", { enumerable: true, get: function() {
6601
+ return timestamp_ts_1.encodeTimestampExtension;
6602
+ } });
6603
+ Object.defineProperty(exports, "decodeTimestampExtension", { enumerable: true, get: function() {
6604
+ return timestamp_ts_1.decodeTimestampExtension;
6605
+ } });
4451
6606
  }
4452
6607
  });
4453
6608
 
@@ -4455,7 +6610,7 @@ var init_secp256k1 = __esm({
4455
6610
  import "dotenv/config";
4456
6611
  import { promises as fs4 } from "node:fs";
4457
6612
  import { descriptions } from "@vultisig/client-shared";
4458
- import { Chain as Chain13, parseKeygenQR, Vultisig as Vultisig6 } from "@vultisig/sdk";
6613
+ import { Chain as Chain14, parseKeygenQR, Vultisig as Vultisig6 } from "@vultisig/sdk";
4459
6614
  import chalk16 from "chalk";
4460
6615
  import { InvalidArgumentError, program as program2 } from "commander";
4461
6616
 
@@ -6993,8 +9148,19 @@ async function previewDryRun(vault, params, dryResult, to) {
6993
9148
  ...warnings.length > 0 ? { warning: warnings.join(". ") } : {}
6994
9149
  };
6995
9150
  if (isJsonOutput()) {
6996
- outputJson(result);
6997
- return result;
9151
+ if (params.amount !== "max") {
9152
+ outputJson(result);
9153
+ return result;
9154
+ }
9155
+ const decimals = dryResult.keysignPayload.coin?.decimals;
9156
+ if (decimals === void 0) throw new Error("Prepared transaction is missing coin decimals");
9157
+ const jsonResult = {
9158
+ ...result,
9159
+ amount: formatBigintAmount(BigInt(dryResult.keysignPayload.toAmount), decimals),
9160
+ isMax: true
9161
+ };
9162
+ outputJson(jsonResult);
9163
+ return jsonResult;
6998
9164
  }
6999
9165
  info(`
7000
9166
  Dry-run preview:`);
@@ -8548,12 +10714,233 @@ async function recoverAddress({ hash, signature }) {
8548
10714
  return publicKeyToAddress(await recoverPublicKey({ hash, signature }));
8549
10715
  }
8550
10716
 
10717
+ // ../../node_modules/viem/_esm/utils/signature/hashTypedData.js
10718
+ init_encodeAbiParameters();
10719
+ init_concat();
10720
+ init_toHex();
10721
+ init_keccak256();
10722
+
10723
+ // ../../node_modules/viem/_esm/utils/typedData.js
10724
+ init_abi();
10725
+ init_address();
10726
+
10727
+ // ../../node_modules/viem/_esm/errors/typedData.js
10728
+ init_stringify();
10729
+ init_base();
10730
+ var InvalidDomainError = class extends BaseError {
10731
+ constructor({ domain }) {
10732
+ super(`Invalid domain "${stringify(domain)}".`, {
10733
+ metaMessages: ["Must be a valid EIP-712 domain."]
10734
+ });
10735
+ }
10736
+ };
10737
+ var InvalidPrimaryTypeError = class extends BaseError {
10738
+ constructor({ primaryType, types }) {
10739
+ super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
10740
+ docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
10741
+ metaMessages: ["Check that the primary type is a key in `types`."]
10742
+ });
10743
+ }
10744
+ };
10745
+ var InvalidStructTypeError = class extends BaseError {
10746
+ constructor({ type }) {
10747
+ super(`Struct type "${type}" is invalid.`, {
10748
+ metaMessages: ["Struct type must not be a Solidity type."],
10749
+ name: "InvalidStructTypeError"
10750
+ });
10751
+ }
10752
+ };
10753
+
10754
+ // ../../node_modules/viem/_esm/utils/typedData.js
10755
+ init_isAddress();
10756
+ init_size();
10757
+ init_toHex();
10758
+ init_regex();
10759
+ function validateTypedData(parameters) {
10760
+ const { domain, message, primaryType, types } = parameters;
10761
+ const validateData = (struct, data) => {
10762
+ for (const param of struct) {
10763
+ const { name, type } = param;
10764
+ const value = data[name];
10765
+ const integerMatch = type.match(integerRegex);
10766
+ if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
10767
+ const [_type, base, size_] = integerMatch;
10768
+ numberToHex(value, {
10769
+ signed: base === "int",
10770
+ size: Number.parseInt(size_, 10) / 8
10771
+ });
10772
+ }
10773
+ if (type === "address" && typeof value === "string" && !isAddress(value))
10774
+ throw new InvalidAddressError2({ address: value });
10775
+ const bytesMatch = type.match(bytesRegex);
10776
+ if (bytesMatch) {
10777
+ const [_type, size_] = bytesMatch;
10778
+ if (size_ && size(value) !== Number.parseInt(size_, 10))
10779
+ throw new BytesSizeMismatchError({
10780
+ expectedSize: Number.parseInt(size_, 10),
10781
+ givenSize: size(value)
10782
+ });
10783
+ }
10784
+ const struct2 = types[type];
10785
+ if (struct2) {
10786
+ validateReference(type);
10787
+ validateData(struct2, value);
10788
+ }
10789
+ }
10790
+ };
10791
+ if (types.EIP712Domain && domain) {
10792
+ if (typeof domain !== "object")
10793
+ throw new InvalidDomainError({ domain });
10794
+ validateData(types.EIP712Domain, domain);
10795
+ }
10796
+ if (primaryType !== "EIP712Domain") {
10797
+ if (types[primaryType])
10798
+ validateData(types[primaryType], message);
10799
+ else
10800
+ throw new InvalidPrimaryTypeError({ primaryType, types });
10801
+ }
10802
+ }
10803
+ function getTypesForEIP712Domain({ domain }) {
10804
+ return [
10805
+ typeof domain?.name === "string" && { name: "name", type: "string" },
10806
+ domain?.version && { name: "version", type: "string" },
10807
+ (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
10808
+ name: "chainId",
10809
+ type: "uint256"
10810
+ },
10811
+ domain?.verifyingContract && {
10812
+ name: "verifyingContract",
10813
+ type: "address"
10814
+ },
10815
+ domain?.salt && { name: "salt", type: "bytes32" }
10816
+ ].filter(Boolean);
10817
+ }
10818
+ function validateReference(type) {
10819
+ if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
10820
+ throw new InvalidStructTypeError({ type });
10821
+ }
10822
+
10823
+ // ../../node_modules/viem/_esm/utils/signature/hashTypedData.js
10824
+ function hashTypedData(parameters) {
10825
+ const { domain = {}, message, primaryType } = parameters;
10826
+ const types = {
10827
+ EIP712Domain: getTypesForEIP712Domain({ domain }),
10828
+ ...parameters.types
10829
+ };
10830
+ validateTypedData({
10831
+ domain,
10832
+ message,
10833
+ primaryType,
10834
+ types
10835
+ });
10836
+ const parts = ["0x1901"];
10837
+ if (domain)
10838
+ parts.push(hashDomain({
10839
+ domain,
10840
+ types
10841
+ }));
10842
+ if (primaryType !== "EIP712Domain")
10843
+ parts.push(hashStruct({
10844
+ data: message,
10845
+ primaryType,
10846
+ types
10847
+ }));
10848
+ return keccak256(concat(parts));
10849
+ }
10850
+ function hashDomain({ domain, types }) {
10851
+ return hashStruct({
10852
+ data: domain,
10853
+ primaryType: "EIP712Domain",
10854
+ types
10855
+ });
10856
+ }
10857
+ function hashStruct({ data, primaryType, types }) {
10858
+ const encoded = encodeData({
10859
+ data,
10860
+ primaryType,
10861
+ types
10862
+ });
10863
+ return keccak256(encoded);
10864
+ }
10865
+ function encodeData({ data, primaryType, types }) {
10866
+ const encodedTypes = [{ type: "bytes32" }];
10867
+ const encodedValues = [hashType({ primaryType, types })];
10868
+ for (const field of types[primaryType]) {
10869
+ const [type, value] = encodeField({
10870
+ types,
10871
+ name: field.name,
10872
+ type: field.type,
10873
+ value: data[field.name]
10874
+ });
10875
+ encodedTypes.push(type);
10876
+ encodedValues.push(value);
10877
+ }
10878
+ return encodeAbiParameters(encodedTypes, encodedValues);
10879
+ }
10880
+ function hashType({ primaryType, types }) {
10881
+ const encodedHashType = toHex(encodeType({ primaryType, types }));
10882
+ return keccak256(encodedHashType);
10883
+ }
10884
+ function encodeType({ primaryType, types }) {
10885
+ let result = "";
10886
+ const unsortedDeps = findTypeDependencies({ primaryType, types });
10887
+ unsortedDeps.delete(primaryType);
10888
+ const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
10889
+ for (const type of deps) {
10890
+ result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
10891
+ }
10892
+ return result;
10893
+ }
10894
+ function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
10895
+ const match = primaryType_.match(/^\w*/u);
10896
+ const primaryType = match?.[0];
10897
+ if (results.has(primaryType) || types[primaryType] === void 0) {
10898
+ return results;
10899
+ }
10900
+ results.add(primaryType);
10901
+ for (const field of types[primaryType]) {
10902
+ findTypeDependencies({ primaryType: field.type, types }, results);
10903
+ }
10904
+ return results;
10905
+ }
10906
+ function encodeField({ types, name, type, value }) {
10907
+ if (types[type] !== void 0) {
10908
+ return [
10909
+ { type: "bytes32" },
10910
+ keccak256(encodeData({ data: value, primaryType: type, types }))
10911
+ ];
10912
+ }
10913
+ if (type === "bytes")
10914
+ return [{ type: "bytes32" }, keccak256(value)];
10915
+ if (type === "string")
10916
+ return [{ type: "bytes32" }, keccak256(toHex(value))];
10917
+ if (type.lastIndexOf("]") === type.length - 1) {
10918
+ const parsedType = type.slice(0, type.lastIndexOf("["));
10919
+ const typeValuePairs = value.map((item) => encodeField({
10920
+ name,
10921
+ type: parsedType,
10922
+ types,
10923
+ value: item
10924
+ }));
10925
+ return [
10926
+ { type: "bytes32" },
10927
+ keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
10928
+ ];
10929
+ }
10930
+ return [{ type }, value];
10931
+ }
10932
+
8551
10933
  // ../../node_modules/viem/_esm/utils/unit/formatUnits.js
8552
10934
  init_Value();
8553
10935
  function formatUnits(value, decimals) {
8554
10936
  return format(value, decimals);
8555
10937
  }
8556
10938
 
10939
+ // ../../node_modules/viem/_esm/index.js
10940
+ init_concat();
10941
+ init_toBytes();
10942
+ init_keccak256();
10943
+
8557
10944
  // src/commands/swap.ts
8558
10945
  async function executeSwapChains(ctx2) {
8559
10946
  const vault = await ctx2.ensureActiveVault();
@@ -8583,8 +10970,8 @@ async function executeSwapQuote(ctx2, options) {
8583
10970
  if (!result.dryRun) throw new Error("unreachable");
8584
10971
  spinner.succeed("Quote received");
8585
10972
  const quote = result.quote;
8586
- const semanticAmount = isMax ? amount : normalizeSwapAmount(amount, quote.fromCoin.decimals);
8587
- const fromAmountDisplay = isMax ? `${formatBigintAmount(quote.maxSwapable, quote.fromCoin.decimals)} (max)` : semanticAmount;
10973
+ const semanticAmount = isMax ? formatBigintAmount(quote.maxSwapable, quote.fromCoin.decimals) : normalizeSwapAmount(amount, quote.fromCoin.decimals);
10974
+ const fromAmountDisplay = isMax ? `${semanticAmount} (max)` : semanticAmount;
8588
10975
  if (isJsonOutput()) {
8589
10976
  outputJson({
8590
10977
  fromChain: options.fromChain,
@@ -9310,6 +11697,14 @@ var AskInterface = class {
9310
11697
  onBalanceSummary: (card) => {
9311
11698
  this.cards.push(card);
9312
11699
  },
11700
+ onHlOrderConfirmation: (card) => {
11701
+ this.cards.push(card);
11702
+ this.outcome = {
11703
+ kind: "blocked",
11704
+ code: "CONFIRMATION_REQUIRED" /* CONFIRMATION_REQUIRED */,
11705
+ detail: "Explicit approval is required before signing this Hyperliquid order."
11706
+ };
11707
+ },
9313
11708
  onYieldOpportunities: (card) => {
9314
11709
  this.yieldCards.push(card);
9315
11710
  },
@@ -9317,6 +11712,9 @@ var AskInterface = class {
9317
11712
  this.polymarketCards.push(card);
9318
11713
  },
9319
11714
  onTurnOutcome: (outcome) => {
11715
+ if (this.outcome?.kind === "blocked" && this.outcome.code === "CONFIRMATION_REQUIRED" /* CONFIRMATION_REQUIRED */) {
11716
+ return;
11717
+ }
9320
11718
  this.outcome = outcome;
9321
11719
  },
9322
11720
  onProposedTransaction: (proposed) => {
@@ -9773,10 +12171,11 @@ import { getChainKind as getChainKind4 } from "@vultisig/sdk";
9773
12171
 
9774
12172
  // src/agent/executor.ts
9775
12173
  import {
9776
- Chain as Chain10,
12174
+ Chain as Chain11,
9777
12175
  chainFeeCoin as chainFeeCoin2,
9778
12176
  computeEip712Hash,
9779
12177
  getChainKind as getChainKind3,
12178
+ getEvmRpcUrl,
9780
12179
  parseThorSwapMemo,
9781
12180
  resolveChainReference,
9782
12181
  toCanonicalEvmSignature,
@@ -9940,6 +12339,234 @@ function sleep2(ms) {
9940
12339
  return new Promise((resolve) => setTimeout(resolve, ms));
9941
12340
  }
9942
12341
 
12342
+ // src/agent/hlOrder.ts
12343
+ var import_msgpack = __toESM(require_dist(), 1);
12344
+ import { Chain as Chain10 } from "@vultisig/sdk";
12345
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
12346
+ var HL_AGENT_TYPES = {
12347
+ Agent: [
12348
+ { name: "source", type: "string" },
12349
+ { name: "connectionId", type: "bytes32" }
12350
+ ]
12351
+ };
12352
+ function isExactStringMember(value, allowed) {
12353
+ return typeof value === "string" && allowed.includes(value);
12354
+ }
12355
+ function nonceBytes(nonce) {
12356
+ if (!Number.isSafeInteger(nonce) || nonce < 0) throw new Error("HL_INVALID_NONCE");
12357
+ const bytes = new Uint8Array(8);
12358
+ let value = BigInt(nonce);
12359
+ for (let i = 7; i >= 0; i--) {
12360
+ bytes[i] = Number(value & 0xffn);
12361
+ value >>= 8n;
12362
+ }
12363
+ return bytes;
12364
+ }
12365
+ function vaultMarker(vaultAddress) {
12366
+ if (!vaultAddress) return new Uint8Array([0]);
12367
+ if (!/^0x[0-9a-f]{40}$/i.test(vaultAddress)) throw new Error("HL_INVALID_VAULT_ADDRESS");
12368
+ return concat([new Uint8Array([1]), hexToBytes(vaultAddress)]);
12369
+ }
12370
+ function computeHlDigest(step) {
12371
+ const packed = (0, import_msgpack.encode)(step.action, { forceIntegerToFloat: false });
12372
+ const connectionId = keccak256(concat([packed, nonceBytes(step.nonce), vaultMarker(step.vault_address)]));
12373
+ return hashTypedData({
12374
+ domain: {
12375
+ name: "Exchange",
12376
+ version: "1",
12377
+ chainId: 1337,
12378
+ verifyingContract: ZERO_ADDRESS
12379
+ },
12380
+ types: HL_AGENT_TYPES,
12381
+ primaryType: "Agent",
12382
+ message: { source: step.is_mainnet ? "a" : "b", connectionId }
12383
+ });
12384
+ }
12385
+ function hasExactObjectKeys(value, allowed) {
12386
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
12387
+ const prototype = Object.getPrototypeOf(value);
12388
+ if (prototype !== Object.prototype && prototype !== null) return false;
12389
+ const keys = Object.keys(value);
12390
+ return keys.length === allowed.length && keys.every((key) => allowed.includes(key));
12391
+ }
12392
+ function isPlainRecord(value) {
12393
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
12394
+ const prototype = Object.getPrototypeOf(value);
12395
+ return prototype === Object.prototype || prototype === null;
12396
+ }
12397
+ function validateOrderAction(action, summary) {
12398
+ if (!hasExactObjectKeys(action, ["type", "orders", "grouping"])) throw new Error("HL_INVALID_ORDER_ACTION_SCHEMA");
12399
+ if (typeof summary.coin !== "string" || !summary.coin.trim()) throw new Error("HL_INVALID_COIN");
12400
+ if (!Number.isInteger(summary.asset_index)) throw new Error("HL_INVALID_ASSET_INDEX");
12401
+ if (!isExactStringMember(action.type, ["order"]) || !Array.isArray(action.orders) || action.orders.length !== 1) {
12402
+ throw new Error("HL_INVALID_ORDER_ACTION");
12403
+ }
12404
+ if (!isExactStringMember(action.grouping, ["na"])) throw new Error("HL_INVALID_ORDER_GROUPING");
12405
+ const order = action.orders[0];
12406
+ if (!hasExactObjectKeys(order, ["a", "b", "p", "r", "s", "t"])) throw new Error("HL_INVALID_ORDER_SCHEMA");
12407
+ if (!Number.isInteger(order.a) || typeof order.b !== "boolean") throw new Error("HL_INVALID_ORDER_ACTION");
12408
+ if (order.a !== summary.asset_index) throw new Error("HL_ASSET_MISMATCH");
12409
+ if (typeof order.p !== "string" || !Number.isFinite(Number(order.p)) || Number(order.p) <= 0) {
12410
+ throw new Error("HL_INVALID_ORDER_PRICE");
12411
+ }
12412
+ if (typeof order.s !== "string" || !Number.isFinite(Number(order.s)) || Number(order.s) <= 0) {
12413
+ throw new Error("HL_INVALID_ORDER_SIZE");
12414
+ }
12415
+ if (summary.size !== order.s) {
12416
+ throw new Error("HL_ORDER_SIZE_MISMATCH");
12417
+ }
12418
+ if (summary.notional_usd !== multiplyDecimalStrings(order.p, order.s)) {
12419
+ throw new Error("HL_INVALID_ORDER_NOTIONAL");
12420
+ }
12421
+ if (summary.price_cap !== order.p) throw new Error("HL_ORDER_PRICE_CAP_MISMATCH");
12422
+ if (!hasExactObjectKeys(order.t, ["limit"])) throw new Error("HL_INVALID_ORDER_TYPE_SCHEMA");
12423
+ const limit = order.t.limit;
12424
+ if (!hasExactObjectKeys(limit, ["tif"])) throw new Error("HL_INVALID_LIMIT_SCHEMA");
12425
+ const tif = limit.tif;
12426
+ if (!isExactStringMember(tif, ["Ioc", "Gtc", "Alo"]) || tif !== summary.tif) throw new Error("HL_TIF_MISMATCH");
12427
+ const expectedOrderType = tif === "Ioc" ? "market" : "limit";
12428
+ if (summary.order_type !== expectedOrderType) throw new Error("HL_ORDER_TYPE_MISMATCH");
12429
+ if (summary.limit_price !== (expectedOrderType === "limit" ? order.p : null))
12430
+ throw new Error("HL_LIMIT_PRICE_MISMATCH");
12431
+ if (order.r !== summary.reduce_only) throw new Error("HL_REDUCE_ONLY_MISMATCH");
12432
+ if (summary.operation === "close" && order.r !== true) throw new Error("HL_CLOSE_NOT_REDUCE_ONLY");
12433
+ const expectedBuy = summary.operation === "open" ? summary.side === "long" : summary.side === "short";
12434
+ if (order.b !== expectedBuy) throw new Error("HL_ORDER_SIDE_MISMATCH");
12435
+ }
12436
+ function multiplyDecimalStrings(left, right) {
12437
+ const parse = (value) => {
12438
+ if (typeof value !== "string" || !/^\d+(?:\.\d+)?$/.test(value)) throw new Error("HL_INVALID_DECIMAL");
12439
+ const [whole2, fraction2 = ""] = value.split(".");
12440
+ return { digits: BigInt(`${whole2}${fraction2}`), scale: fraction2.length };
12441
+ };
12442
+ const a = parse(left);
12443
+ const b = parse(right);
12444
+ const scale = a.scale + b.scale;
12445
+ const raw = (a.digits * b.digits).toString().padStart(scale + 1, "0");
12446
+ if (scale === 0) return raw;
12447
+ const whole = raw.slice(0, -scale);
12448
+ const fraction = raw.slice(-scale).replace(/0+$/, "");
12449
+ return fraction ? `${whole}.${fraction}` : whole;
12450
+ }
12451
+ function validateLeverageAction(action, summary) {
12452
+ if (!hasExactObjectKeys(action, ["type", "asset", "isCross", "leverage"]))
12453
+ throw new Error("HL_INVALID_LEVERAGE_ACTION_SCHEMA");
12454
+ if (!isExactStringMember(action.type, ["updateLeverage"]) || !Number.isInteger(action.asset) || !Number.isInteger(action.leverage)) {
12455
+ throw new Error("HL_INVALID_LEVERAGE_ACTION");
12456
+ }
12457
+ if (typeof action.isCross !== "boolean" || action.leverage !== summary.leverage) {
12458
+ throw new Error("HL_LEVERAGE_MISMATCH");
12459
+ }
12460
+ if (action.asset !== summary.asset_index) throw new Error("HL_LEVERAGE_ASSET_MISMATCH");
12461
+ if (action.leverage < 1 || action.leverage > 100) {
12462
+ throw new Error("HL_INVALID_LEVERAGE");
12463
+ }
12464
+ const expectedCross = summary.margin_mode !== "isolated";
12465
+ if (action.isCross !== expectedCross) throw new Error("HL_MARGIN_MODE_MISMATCH");
12466
+ }
12467
+ function validatePayloadShape(payload) {
12468
+ if (!isPlainRecord(payload)) throw new Error("HL_INVALID_PAYLOAD");
12469
+ if (!isPlainRecord(payload.summary)) throw new Error("HL_INVALID_SUMMARY");
12470
+ if (!isPlainRecord(payload.asset_binding)) throw new Error("HL_INVALID_ASSET_BINDING");
12471
+ if (!Array.isArray(payload.steps)) throw new Error("HL_INVALID_STEPS");
12472
+ for (const key of ["operation", "side", "margin_mode", "reduce_only", "leverage"]) {
12473
+ if (key in payload) throw new Error("HL_CONFLICTING_TOP_LEVEL_FIELD");
12474
+ }
12475
+ }
12476
+ function validateSummary(summary) {
12477
+ if (!isExactStringMember(summary.operation, ["open", "close"])) throw new Error("HL_INVALID_OPERATION");
12478
+ if (!isExactStringMember(summary.side, ["long", "short"])) throw new Error("HL_INVALID_SIDE");
12479
+ if (!isExactStringMember(summary.order_type, ["market", "limit"])) throw new Error("HL_INVALID_ORDER_TYPE");
12480
+ if (!isExactStringMember(summary.tif, ["Ioc", "Gtc", "Alo"])) throw new Error("HL_INVALID_TIF");
12481
+ if (typeof summary.coin !== "string" || !summary.coin.trim()) throw new Error("HL_INVALID_COIN");
12482
+ if (!Number.isInteger(summary.asset_index)) throw new Error("HL_INVALID_ASSET_INDEX");
12483
+ if (summary.margin_mode !== void 0 && !isExactStringMember(summary.margin_mode, ["cross", "isolated"])) {
12484
+ throw new Error("HL_INVALID_MARGIN_MODE");
12485
+ }
12486
+ if (typeof summary.reduce_only !== "boolean") throw new Error("HL_INVALID_REDUCE_ONLY");
12487
+ }
12488
+ async function validateRequestBinding(payload, expected, vault, now) {
12489
+ if (payload.order_ref !== expected.orderRef || payload.conversation_id !== expected.conversationId) {
12490
+ throw new Error("HL_REFERENCE_MISMATCH");
12491
+ }
12492
+ if (typeof payload.owner_public_key !== "string") throw new Error("HL_INVALID_OWNER_PUBLIC_KEY");
12493
+ if (payload.owner_public_key.toLowerCase() !== expected.publicKey.toLowerCase()) throw new Error("HL_OWNER_MISMATCH");
12494
+ if (typeof payload.vault_address !== "string") throw new Error("HL_INVALID_VAULT_ADDRESS");
12495
+ const localAddress = await vault.address(Chain10.Ethereum);
12496
+ if (payload.vault_address.toLowerCase() !== localAddress.toLowerCase()) throw new Error("HL_VAULT_ADDRESS_MISMATCH");
12497
+ if (typeof payload.expires_at !== "string") throw new Error("HL_INVALID_EXPIRY");
12498
+ const expiry = Date.parse(payload.expires_at);
12499
+ if (!Number.isFinite(expiry) || expiry <= now) throw new Error("HL_ORDER_EXPIRED");
12500
+ if (expiry - now > 10 * 6e4) throw new Error("HL_EXPIRY_OUT_OF_RANGE");
12501
+ }
12502
+ function validateSteps(payload) {
12503
+ if (payload.steps.length < 1 || payload.steps.length > 2) throw new Error("HL_INVALID_STEP_COUNT");
12504
+ if (payload.steps.some((step) => !isPlainRecord(step) || !isPlainRecord(step.action)))
12505
+ throw new Error("HL_INVALID_STEP");
12506
+ if (payload.steps.some((step) => !isExactStringMember(step.kind, ["update_leverage", "order"])))
12507
+ throw new Error("HL_INVALID_STEP_KIND");
12508
+ if (payload.steps.some((step) => typeof step.is_mainnet !== "boolean")) throw new Error("HL_INVALID_NETWORK_FLAG");
12509
+ const isMainnet = payload.steps[0].is_mainnet;
12510
+ if (payload.steps.some((step) => step.is_mainnet !== isMainnet)) throw new Error("HL_NETWORK_MISMATCH");
12511
+ return payload.steps.filter((step) => step.kind === "order");
12512
+ }
12513
+ function validateCeremony(payload, orderSteps) {
12514
+ const leverageSteps = payload.steps.filter((step) => step.kind === "update_leverage");
12515
+ if (payload.summary.operation === "open") {
12516
+ if (payload.steps.length !== 2 || payload.steps[0]?.kind !== "update_leverage" || payload.steps[1]?.kind !== "order" || leverageSteps.length !== 1 || orderSteps.length !== 1 || payload.summary.leverage === void 0 || payload.summary.margin_mode === void 0 || payload.summary.reduce_only !== false)
12517
+ throw new Error("HL_INVALID_OPEN_CEREMONY");
12518
+ return;
12519
+ }
12520
+ if (payload.steps.length !== 1 || payload.steps[0]?.kind !== "order" || orderSteps.length !== 1 || leverageSteps.length !== 0 || payload.summary.leverage !== void 0 || payload.summary.margin_mode !== void 0 || payload.summary.reduce_only !== true)
12521
+ throw new Error("HL_INVALID_CLOSE_CEREMONY");
12522
+ }
12523
+ function validateSignedSteps(payload) {
12524
+ for (const step of payload.steps) {
12525
+ if (typeof step.digest !== "string") throw new Error("HL_INVALID_DIGEST");
12526
+ const computed = computeHlDigest(step);
12527
+ if (computed.toLowerCase() !== step.digest.toLowerCase()) throw new Error("HL_DIGEST_MISMATCH");
12528
+ if (step.kind === "order") validateOrderAction(step.action, payload.summary);
12529
+ else validateLeverageAction(step.action, payload.summary);
12530
+ }
12531
+ }
12532
+ async function validateHlSigningPayload(payload, expected, vault, now = Date.now()) {
12533
+ validatePayloadShape(payload);
12534
+ validateSummary(payload.summary);
12535
+ await validateRequestBinding(payload, expected, vault, now);
12536
+ const orderSteps = validateSteps(payload);
12537
+ validateCeremony(payload, orderSteps);
12538
+ if (payload.asset_binding.coin !== payload.summary.coin || payload.asset_binding.asset_index !== payload.summary.asset_index)
12539
+ throw new Error("HL_ASSET_BINDING_MISMATCH");
12540
+ validateSignedSteps(payload);
12541
+ if (expected.digest && orderSteps[0]?.digest.toLowerCase() !== expected.digest.toLowerCase()) {
12542
+ throw new Error("HL_EXPECTED_DIGEST_MISMATCH");
12543
+ }
12544
+ }
12545
+ function formatHlConfirmation(payload) {
12546
+ const s = payload.summary;
12547
+ const network = payload.steps[0]?.is_mainnet === false ? "Testnet" : "Mainnet";
12548
+ const leverage = s.leverage === void 0 ? "" : ` at ${s.leverage}x ${s.margin_mode ?? "cross"}`;
12549
+ const price = s.limit_price === null ? `market max execution price $${s.price_cap}` : `limit $${s.limit_price}`;
12550
+ return `Hyperliquid ${network} ${s.operation} ${s.side} ${s.size} ${s.coin} (asset #${s.asset_index}, signed notional $${s.notional_usd})${leverage}; ${s.order_type}/${s.tif}, ${price}, reduce-only=${s.reduce_only}. This signs and submits a live leveraged order.`;
12551
+ }
12552
+ async function pollHlOrderStatus(transport, params, initial, options = {}) {
12553
+ if (initial.state !== "accepted" && initial.state !== "submitting") return initial;
12554
+ const attempts = options.attempts ?? 20;
12555
+ const sleep4 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
12556
+ let status = initial;
12557
+ for (let i = 1; i < attempts && (status.state === "accepted" || status.state === "submitting"); i++) {
12558
+ await sleep4(options.intervalMs ?? 1e3);
12559
+ try {
12560
+ status = await transport.getHlOrderStatus(params.orderRef, params.conversationId, params.publicKey);
12561
+ } catch {
12562
+ }
12563
+ }
12564
+ return status;
12565
+ }
12566
+ function isHlOrderFailure(status) {
12567
+ return status.state === "rejected" || status.state === "cancelled";
12568
+ }
12569
+
9943
12570
  // src/agent/executor.ts
9944
12571
  var EVM_CHAINS = /* @__PURE__ */ new Set([
9945
12572
  "Ethereum",
@@ -9956,21 +12583,7 @@ var EVM_CHAINS = /* @__PURE__ */ new Set([
9956
12583
  "Hyperliquid",
9957
12584
  "Sei"
9958
12585
  ]);
9959
- var EVM_GAS_RPC = {
9960
- Ethereum: "https://ethereum-rpc.publicnode.com",
9961
- BSC: "https://bsc-dataseed.binance.org",
9962
- Polygon: "https://polygon-bor-rpc.publicnode.com",
9963
- Avalanche: "https://api.avax.network/ext/bc/C/rpc",
9964
- Arbitrum: "https://arb1.arbitrum.io/rpc",
9965
- Optimism: "https://mainnet.optimism.io",
9966
- Base: "https://mainnet.base.org",
9967
- Blast: "https://rpc.blast.io",
9968
- Zksync: "https://mainnet.era.zksync.io",
9969
- Mantle: "https://rpc.mantle.xyz",
9970
- CronosChain: "https://cronos-evm-rpc.publicnode.com",
9971
- Hyperliquid: "https://rpc.hyperliquid.xyz/evm",
9972
- Sei: "https://evm-rpc.sei-apis.com"
9973
- };
12586
+ var isEvmChain = (chain) => EVM_CHAINS.has(chain);
9974
12587
  var AgentExecutor = class {
9975
12588
  vault;
9976
12589
  /** Owning SDK (optional); used for address book backed by app storage */
@@ -9996,6 +12609,7 @@ var AgentExecutor = class {
9996
12609
  // fingerprints so two different vaults sending an identical tx don't collide
9997
12610
  // in the single global journal (see BroadcastIntent.owner).
9998
12611
  vaultPublicKey;
12612
+ consumedHlOrderRefs = /* @__PURE__ */ new Set();
9999
12613
  constructor(vault, verbose = false, vaultId, vultisig) {
10000
12614
  this.vault = vault;
10001
12615
  this.verbose = verbose;
@@ -10005,6 +12619,79 @@ var AgentExecutor = class {
10005
12619
  this.stateStore = new VaultStateStore(vaultId);
10006
12620
  }
10007
12621
  }
12622
+ async retrieveHlOrder(transport, input, conversationId) {
12623
+ const orderRef = typeof input.order_ref === "string" ? input.order_ref : "";
12624
+ if (!/^[0-9a-f-]{16,64}$/i.test(orderRef)) throw new Error("HL_INVALID_ORDER_REFERENCE");
12625
+ if (this.consumedHlOrderRefs.has(orderRef)) throw new Error("HL_ORDER_REFERENCE_REPLAYED");
12626
+ const payload = await transport.retrieveHlOrderSigningPayload(orderRef, conversationId, this.vaultPublicKey);
12627
+ this.consumedHlOrderRefs.add(orderRef);
12628
+ await validateHlSigningPayload(
12629
+ payload,
12630
+ {
12631
+ orderRef,
12632
+ conversationId,
12633
+ publicKey: this.vaultPublicKey,
12634
+ digest: typeof input.digest === "string" ? input.digest : void 0
12635
+ },
12636
+ this.vault
12637
+ );
12638
+ return payload;
12639
+ }
12640
+ async signAndSubmitHlOrder(transport, payload) {
12641
+ return this.runTool("hl_order", async () => {
12642
+ if (this.vault.isEncrypted && !this.vault.isUnlocked?.() && this.password) {
12643
+ await this.vault.unlock?.(this.password);
12644
+ }
12645
+ const expectedAddress = await this.vault.address(Chain11.Ethereum);
12646
+ const signatures = [];
12647
+ for (const step of payload.steps) {
12648
+ const signed = await this.vault.signBytes({
12649
+ data: step.digest,
12650
+ chain: Chain11.Ethereum
12651
+ });
12652
+ const canonical = toCanonicalEvmSignature(signed.signature, signed.recovery ?? 0);
12653
+ const v = canonical.recovery + 27;
12654
+ const wireSignature = `0x${canonical.r}${canonical.s}${v.toString(16).padStart(2, "0")}`;
12655
+ const recovered = await recoverAddress({
12656
+ hash: step.digest,
12657
+ signature: wireSignature
12658
+ });
12659
+ if (recovered.toLowerCase() !== expectedAddress.toLowerCase()) {
12660
+ throw new Error("HL_SIGNATURE_RECOVERY_MISMATCH");
12661
+ }
12662
+ signatures.push({
12663
+ kind: step.kind,
12664
+ digest: step.digest,
12665
+ r: `0x${canonical.r}`,
12666
+ s: `0x${canonical.s}`,
12667
+ v
12668
+ });
12669
+ }
12670
+ const params = {
12671
+ orderRef: payload.order_ref,
12672
+ conversationId: payload.conversation_id,
12673
+ publicKey: this.vaultPublicKey
12674
+ };
12675
+ const submitted = await transport.submitHlOrder(
12676
+ params.orderRef,
12677
+ params.conversationId,
12678
+ params.publicKey,
12679
+ signatures
12680
+ );
12681
+ const status = await pollHlOrderStatus(transport, params, submitted);
12682
+ if (isHlOrderFailure(status)) {
12683
+ throw new Error(`HL_ORDER_${status.state.toUpperCase()}: ${status.reason ?? "venue did not accept the order"}`);
12684
+ }
12685
+ return {
12686
+ order_ref: payload.order_ref,
12687
+ state: status.state,
12688
+ order_id: status.order_id,
12689
+ filled_size: status.filled_size,
12690
+ average_price: status.average_price,
12691
+ reason: status.reason
12692
+ };
12693
+ });
12694
+ }
10008
12695
  setPassword(password) {
10009
12696
  this.password = password;
10010
12697
  }
@@ -10097,7 +12784,7 @@ var AgentExecutor = class {
10097
12784
  return false;
10098
12785
  }
10099
12786
  const chain2 = approvalChain;
10100
- if (!EVM_CHAINS.has(chain2)) {
12787
+ if (!isEvmChain(chain2)) {
10101
12788
  if (this.verbose)
10102
12789
  process.stderr.write(
10103
12790
  `[executor] rejecting multi-leg envelope on non-EVM chain ${chain2}: signMultiLeg is EVM-only
@@ -10135,7 +12822,7 @@ var AgentExecutor = class {
10135
12822
  if (!nestedTx && txReadyData && typeof txReadyData === "object") {
10136
12823
  const txArgs = txReadyData.txArgs;
10137
12824
  if (txArgs && typeof txArgs === "object" && typeof txArgs.to === "string" && typeof txArgs.amount === "string") {
10138
- const chain2 = resolveChainFromTxReady(txReadyData) || Chain10.Ethereum;
12825
+ const chain2 = resolveChainFromTxReady(txReadyData) || Chain11.Ethereum;
10139
12826
  if (getChainKind3(chain2) !== "evm") {
10140
12827
  this.pendingPayloads.clear();
10141
12828
  this.pendingLegs = [];
@@ -10160,7 +12847,7 @@ var AgentExecutor = class {
10160
12847
  `);
10161
12848
  return false;
10162
12849
  }
10163
- const chain = resolveChainFromTxReady(txReadyData) || Chain10.Ethereum;
12850
+ const chain = resolveChainFromTxReady(txReadyData) || Chain11.Ethereum;
10164
12851
  this.pendingPayloads.clear();
10165
12852
  this.pendingLegs = [];
10166
12853
  this.pendingPayloads.set("latest", {
@@ -10454,7 +13141,9 @@ var AgentExecutor = class {
10454
13141
  }
10455
13142
  const isMultiLeg = !!payload.__multiLeg;
10456
13143
  const primaryIntent = isMultiLeg ? this.buildBroadcastIntent(payload, chain, { txArgs: payload.txArgs }) : this.buildBroadcastIntent(payload, chain);
10457
- const approveIntent = isMultiLeg ? this.buildBroadcastIntent(payload, chain, { txArgs: payload.approvalTxArgs }) : void 0;
13144
+ const approveIntent = isMultiLeg ? this.buildBroadcastIntent(payload, chain, {
13145
+ txArgs: payload.approvalTxArgs
13146
+ }) : void 0;
10458
13147
  const primaryFp = computeFingerprint(primaryIntent);
10459
13148
  const approveFp = approveIntent ? computeFingerprint(approveIntent) : void 0;
10460
13149
  assertNoRecentDuplicate(primaryIntent, { force: this.forceBroadcast });
@@ -10545,7 +13234,7 @@ var AgentExecutor = class {
10545
13234
  `signNonEvmServerTx: dispatcher chain '${chain}' disagrees with envelope chain '${txArgs.chain}'`
10546
13235
  );
10547
13236
  }
10548
- if (txArgs.msg_type === "deposit" && (chain === Chain10.THORChain || chain === Chain10.MayaChain)) {
13237
+ if (txArgs.msg_type === "deposit" && (chain === Chain11.THORChain || chain === Chain11.MayaChain)) {
10549
13238
  const memo = typeof txArgs.memo === "string" ? txArgs.memo : "";
10550
13239
  if (memo.startsWith("=:")) {
10551
13240
  return this.signThorMsgDepositSwap(serverTxData, chain);
@@ -10618,7 +13307,7 @@ var AgentExecutor = class {
10618
13307
  );
10619
13308
  }
10620
13309
  const toChain = parsed.toChain;
10621
- const fromSymbol = chain === Chain10.THORChain ? "RUNE" : "CACAO";
13310
+ const fromSymbol = chain === Chain11.THORChain ? "RUNE" : "CACAO";
10622
13311
  const amountRaw = typeof txArgs.amount === "string" ? txArgs.amount : void 0;
10623
13312
  if (!amountRaw) {
10624
13313
  throw new VaultError3(
@@ -11000,7 +13689,7 @@ var AgentExecutor = class {
11000
13689
  * Releases any previously held lock first (e.g. from an abandoned build).
11001
13690
  */
11002
13691
  async acquireEvmLockIfNeeded(chain) {
11003
- if (!this.stateStore || !EVM_CHAINS.has(chain)) return;
13692
+ if (!this.stateStore || !isEvmChain(chain)) return;
11004
13693
  await this.releaseEvmLock(chain);
11005
13694
  const release = await this.stateStore.acquireChainLock(chain);
11006
13695
  this.chainLockReleases.set(chain, release);
@@ -11029,7 +13718,7 @@ var AgentExecutor = class {
11029
13718
  * dropped and local state is stale.
11030
13719
  */
11031
13720
  async patchEvmNonce(chain, payload) {
11032
- if (!this.stateStore || !EVM_CHAINS.has(chain)) return;
13721
+ if (!this.stateStore || !isEvmChain(chain)) return;
11033
13722
  const bs = payload.blockchainSpecific;
11034
13723
  if (!bs || bs.case !== "ethereumSpecific") return;
11035
13724
  const rpcNonce = bs.value.nonce;
@@ -11081,11 +13770,10 @@ var AgentExecutor = class {
11081
13770
  * Compensates for gas price drift between build time and sign time.
11082
13771
  */
11083
13772
  async patchEvmGas(chain, payload) {
11084
- if (!EVM_CHAINS.has(chain)) return;
13773
+ if (!isEvmChain(chain)) return;
11085
13774
  const bs = payload.blockchainSpecific;
11086
13775
  if (!bs || bs.case !== "ethereumSpecific") return;
11087
- const rpcUrl = EVM_GAS_RPC[chain];
11088
- if (!rpcUrl) return;
13776
+ const rpcUrl = getEvmRpcUrl(chain);
11089
13777
  try {
11090
13778
  const res = await fetch(rpcUrl, {
11091
13779
  method: "POST",
@@ -11127,8 +13815,8 @@ var AgentExecutor = class {
11127
13815
  * Returns null if the RPC call fails (non-fatal).
11128
13816
  */
11129
13817
  async fetchEvmPendingNonce(chain) {
11130
- const rpcUrl = EVM_GAS_RPC[chain];
11131
- if (!rpcUrl) return null;
13818
+ if (!isEvmChain(chain)) return null;
13819
+ const rpcUrl = getEvmRpcUrl(chain);
11132
13820
  try {
11133
13821
  const address = await this.vault.address(chain);
11134
13822
  const res = await fetch(rpcUrl, {
@@ -11156,7 +13844,7 @@ var AgentExecutor = class {
11156
13844
  * For approve+swap flows with N message hashes, the highest nonce used is base + N - 1.
11157
13845
  */
11158
13846
  recordEvmNonceFromPayload(chain, payload, numTxs) {
11159
- if (!this.stateStore || !EVM_CHAINS.has(chain)) return;
13847
+ if (!this.stateStore || !isEvmChain(chain)) return;
11160
13848
  const bs = payload.blockchainSpecific;
11161
13849
  if (!bs || bs.case !== "ethereumSpecific") return;
11162
13850
  const baseNonce = bs.value.nonce;
@@ -11237,11 +13925,11 @@ var AgentExecutor = class {
11237
13925
  `);
11238
13926
  const chainName = params.chain;
11239
13927
  const chainId = domain.chainId;
11240
- let chain = Chain10.Ethereum;
13928
+ let chain = Chain11.Ethereum;
11241
13929
  if (chainName) {
11242
- chain = resolveChain(chainName) || Chain10.Ethereum;
13930
+ chain = resolveChain(chainName) || Chain11.Ethereum;
11243
13931
  } else if (chainId) {
11244
- chain = resolveChainId(chainId) || Chain10.Ethereum;
13932
+ chain = resolveChainId(chainId) || Chain11.Ethereum;
11245
13933
  }
11246
13934
  const sigResult = await this.vault.signBytes({
11247
13935
  data: eip712Hash,
@@ -11465,7 +14153,7 @@ function asRecord(value) {
11465
14153
  }
11466
14154
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
11467
14155
  }
11468
- function isAddress(value) {
14156
+ function isAddress2(value) {
11469
14157
  return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value);
11470
14158
  }
11471
14159
  function isCalldata(value) {
@@ -11485,7 +14173,7 @@ function normalizeGasLimit(value) {
11485
14173
  return void 0;
11486
14174
  }
11487
14175
  function extractLeg(obj) {
11488
- const to = isAddress(obj.to) ? obj.to : isAddress(obj.to_address) ? obj.to_address : void 0;
14176
+ const to = isAddress2(obj.to) ? obj.to : isAddress2(obj.to_address) ? obj.to_address : void 0;
11489
14177
  const data = isCalldata(obj.data) ? obj.data : isCalldata(obj.calldata) ? obj.calldata : void 0;
11490
14178
  if (!to || !data) return null;
11491
14179
  const leg = { to, value: normalizeValue(obj.value), data };
@@ -11641,7 +14329,7 @@ function payloadLooksSignable(payload) {
11641
14329
  }
11642
14330
  function legSignable(legObj) {
11643
14331
  const nested = asRecord(legObj.tx) || asRecord(legObj.swap_tx) || asRecord(legObj.send_tx) || asRecord(legObj.txArgs?.tx);
11644
- if (nested && isAddress(nested.to)) return true;
14332
+ if (nested && isAddress2(nested.to)) return true;
11645
14333
  const txArgs = asRecord(legObj.txArgs);
11646
14334
  if (txArgs && typeof txArgs.to === "string" && typeof txArgs.amount === "string") return true;
11647
14335
  return false;
@@ -11676,6 +14364,26 @@ var AgentStreamIdleTimeoutError = class extends Error {
11676
14364
  timeoutMs;
11677
14365
  code = "TIMEOUT" /* TIMEOUT */;
11678
14366
  };
14367
+ var HL_ORDER_BUILD_TOOLS = /* @__PURE__ */ new Set(["build_hyperliquid_open_position", "build_hyperliquid_close_position"]);
14368
+ function deriveHlOrderClientAction(toolName, output) {
14369
+ if (!HL_ORDER_BUILD_TOOLS.has(toolName)) return null;
14370
+ let value = output;
14371
+ if (typeof value === "string") {
14372
+ try {
14373
+ value = JSON.parse(value);
14374
+ } catch {
14375
+ return null;
14376
+ }
14377
+ }
14378
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
14379
+ const result = value;
14380
+ const expectedAction = toolName === "build_hyperliquid_open_position" ? "open" : "close";
14381
+ const expectedReduceOnly = expectedAction === "close";
14382
+ if (result.surface !== "hyperliquid_order" || result.status !== "ready_to_sign" || result.action !== expectedAction || typeof result.order_ref !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(result.order_ref) || typeof result.coin !== "string" || !Number.isInteger(result.asset_index) || typeof result.wire_size !== "string" || typeof result.price_cap !== "string" || typeof result.wire_notional_usd !== "string" || !["Ioc", "Gtc", "Alo"].includes(String(result.tif)) || result.reduce_only !== expectedReduceOnly) {
14383
+ return null;
14384
+ }
14385
+ return { order_ref: result.order_ref };
14386
+ }
11679
14387
  function v1StatusFromType(type) {
11680
14388
  switch (type) {
11681
14389
  case "tool-input-start":
@@ -11838,7 +14546,10 @@ var AgentClient = class {
11838
14546
  try {
11839
14547
  res = await fetch(`${this.baseUrl}/auth/token`, {
11840
14548
  method: "POST",
11841
- headers: { "Content-Type": "application/json", ...this.profileHeader() },
14549
+ headers: {
14550
+ "Content-Type": "application/json",
14551
+ ...this.profileHeader()
14552
+ },
11842
14553
  body: JSON.stringify(req),
11843
14554
  signal: this.timeoutSignal()
11844
14555
  });
@@ -11858,7 +14569,9 @@ var AgentClient = class {
11858
14569
  // ============================================================================
11859
14570
  async healthCheck() {
11860
14571
  try {
11861
- const res = await fetch(`${this.baseUrl}/healthz`, { signal: this.timeoutSignal() });
14572
+ const res = await fetch(`${this.baseUrl}/healthz`, {
14573
+ signal: this.timeoutSignal()
14574
+ });
11862
14575
  return res.ok;
11863
14576
  } catch {
11864
14577
  return false;
@@ -11884,6 +14597,28 @@ var AgentClient = class {
11884
14597
  public_key: publicKey
11885
14598
  });
11886
14599
  }
14600
+ async retrieveHlOrderSigningPayload(orderRef, conversationId, publicKey) {
14601
+ return this.post(
14602
+ `/agent/hyperliquid/orders/${encodeURIComponent(orderRef)}/signing-payload`,
14603
+ {
14604
+ conversation_id: conversationId,
14605
+ public_key: publicKey
14606
+ }
14607
+ );
14608
+ }
14609
+ async submitHlOrder(orderRef, conversationId, publicKey, signatures) {
14610
+ return this.post(`/agent/hyperliquid/orders/${encodeURIComponent(orderRef)}/submit`, {
14611
+ conversation_id: conversationId,
14612
+ public_key: publicKey,
14613
+ signatures
14614
+ });
14615
+ }
14616
+ async getHlOrderStatus(orderRef, conversationId, publicKey) {
14617
+ return this.post(`/agent/hyperliquid/orders/${encodeURIComponent(orderRef)}/status`, {
14618
+ conversation_id: conversationId,
14619
+ public_key: publicKey
14620
+ });
14621
+ }
11887
14622
  // ============================================================================
11888
14623
  // Messages - JSON mode
11889
14624
  // ============================================================================
@@ -12145,7 +14880,12 @@ var AgentClient = class {
12145
14880
  `);
12146
14881
  let warning = result.protocolWarnings[0];
12147
14882
  if (!warning) {
12148
- warning = { code: "PROTOCOL_DRIFT", message: "", count: 0, eventTypes: [] };
14883
+ warning = {
14884
+ code: "PROTOCOL_DRIFT",
14885
+ message: "",
14886
+ count: 0,
14887
+ eventTypes: []
14888
+ };
12149
14889
  result.protocolWarnings.push(warning);
12150
14890
  }
12151
14891
  warning.count += 1;
@@ -12207,8 +14947,20 @@ var AgentClient = class {
12207
14947
  const toolName = inlineName ?? (callId ? toolNameByCallId.get(callId) : void 0);
12208
14948
  const label = typeof parsed.label === "string" ? parsed.label : void 0;
12209
14949
  this.maybeEmitClientSideToolCall(parsed, callbacks, v1Type, callId, toolName);
12210
- const ok = deriveToolDoneOk(status, parsed.output, v1Type);
14950
+ const hlOrderAction = status === "done" && toolName && HL_ORDER_BUILD_TOOLS.has(toolName) ? deriveHlOrderClientAction(toolName, parsed.output) : void 0;
14951
+ const derivedOk = deriveToolDoneOk(status, parsed.output, v1Type);
14952
+ const ok = hlOrderAction === null ? false : derivedOk;
12211
14953
  if (status && toolName) callbacks.onToolProgress?.(toolName, status, label, ok);
14954
+ if (status === "done" && toolName && HL_ORDER_BUILD_TOOLS.has(toolName)) {
14955
+ if (hlOrderAction && callId && callbacks.onClientSideToolCall) {
14956
+ callbacks.onClientSideToolCall(`${callId}:hl_order`, "hl_order", hlOrderAction);
14957
+ } else {
14958
+ callbacks.onError?.(
14959
+ "Hyperliquid preview was not delivered as a complete ready-to-sign action.",
14960
+ "INVALID_INPUT" /* INVALID_INPUT */
14961
+ );
14962
+ }
14963
+ }
12212
14964
  this.maybeSignToolOutput(status, toolName, parsed.output, callbacks, v1Type);
12213
14965
  if (status === "done" && callId) toolNameByCallId.delete(callId);
12214
14966
  }
@@ -12768,14 +15520,13 @@ import {
12768
15520
  statSync as statSync3,
12769
15521
  writeFileSync as writeFileSync3
12770
15522
  } from "node:fs";
12771
- import { homedir } from "node:os";
12772
15523
  import { dirname as dirname2, join as join3 } from "node:path";
15524
+ import { getVultisigConfigDir as getVultisigConfigDir3 } from "@vultisig/client-shared";
12773
15525
  var LOCK_RETRY_MS = 25;
12774
15526
  var LOCK_MAX_WAIT_MS2 = 5e3;
12775
15527
  var LOCK_STALE_MS2 = 3e4;
12776
15528
  function getTokenCachePath() {
12777
- const dir = process.env.VULTISIG_CONFIG_DIR ?? join3(homedir(), ".vultisig");
12778
- return join3(dir, "agent-tokens.json");
15529
+ return join3(getVultisigConfigDir3(), "agent-tokens.json");
12779
15530
  }
12780
15531
  function tokenCacheKey(scope) {
12781
15532
  return JSON.stringify([scope.publicKey, scope.backendUrl.replace(/\/+$/, ""), scope.profile ?? ""]);
@@ -12911,7 +15662,7 @@ async function clearCachedToken(scope) {
12911
15662
  }
12912
15663
 
12913
15664
  // src/agent/session.ts
12914
- var PASSWORD_REQUIRED_TOOLS = /* @__PURE__ */ new Set(["sign_typed_data", "sign_tx"]);
15665
+ var PASSWORD_REQUIRED_TOOLS = /* @__PURE__ */ new Set(["sign_typed_data", "sign_tx", "hl_order"]);
12915
15666
  var AUTO_SUBMIT_MARKERS = /* @__PURE__ */ new Set([
12916
15667
  "__pm_auto_submit",
12917
15668
  "__pm_auto_submit_batch",
@@ -12933,7 +15684,8 @@ var BACKEND_CLIENT_SIDE_TOOL_NAMES = [
12933
15684
  "delete_policy",
12934
15685
  "sign_typed_data",
12935
15686
  "polymarket_sign_bet",
12936
- "polymarket_sign_batch"
15687
+ "polymarket_sign_batch",
15688
+ "hl_order"
12937
15689
  ];
12938
15690
  var CLIENT_SIDE_DISPATCH_TOOL_NAMES = /* @__PURE__ */ new Set([
12939
15691
  ...BACKEND_CLIENT_SIDE_TOOL_NAMES,
@@ -12944,6 +15696,11 @@ var PROPOSED_SUMMARY_MAX_CHARS = 500;
12944
15696
  function capSigningSummary(summary) {
12945
15697
  return summary.length > PROPOSED_SUMMARY_MAX_CHARS ? `${summary.slice(0, PROPOSED_SUMMARY_MAX_CHARS)}\u2026` : summary;
12946
15698
  }
15699
+ function applyAgentMode(request, config) {
15700
+ if (config.viaAgent || config.askMode) {
15701
+ request.via_agent = true;
15702
+ }
15703
+ }
12947
15704
  var RECOVERY_POLL_INTERVAL_MS = 2e3;
12948
15705
  var RECOVERY_MAX_POLLS = 90;
12949
15706
  var TX_CONFIRM_POLL_INTERVAL_MS = 3e3;
@@ -13017,6 +15774,9 @@ var AgentSession = class {
13017
15774
  pushService = null;
13018
15775
  // Flushed into context.recent_actions on the next outbound request.
13019
15776
  pendingToolResults = [];
15777
+ terminalHlConfirmation = false;
15778
+ firstHlOrderRef = null;
15779
+ seenHlOrderRefs = /* @__PURE__ */ new Set();
13020
15780
  // Snapshot, taken the instant sendMessage's catch fires (BEFORE it clears the
13021
15781
  // queue), of whether an already-broadcast tx result was still UNDELIVERED to
13022
15782
  // the backend. This is the true "ack failed" signal: a successful broadcast
@@ -13151,7 +15911,9 @@ var AgentSession = class {
13151
15911
  new Error(
13152
15912
  `Session ${this.config.sessionId} could not be resumed (${err?.message ?? "unknown error"}); refusing to execute the request without its conversation context`
13153
15913
  ),
13154
- { code: isAuthError(err) ? "AUTH_FAILED" /* AUTH_FAILED */ : "SESSION_NOT_FOUND" /* SESSION_NOT_FOUND */ }
15914
+ {
15915
+ code: isAuthError(err) ? "AUTH_FAILED" /* AUTH_FAILED */ : "SESSION_NOT_FOUND" /* SESSION_NOT_FOUND */
15916
+ }
13155
15917
  );
13156
15918
  }
13157
15919
  this.conversationId = null;
@@ -13273,6 +16035,9 @@ var AgentSession = class {
13273
16035
  throw new Error("Session not initialized");
13274
16036
  }
13275
16037
  this.abortController = new AbortController();
16038
+ this.terminalHlConfirmation = false;
16039
+ this.firstHlOrderRef = null;
16040
+ this.seenHlOrderRefs = /* @__PURE__ */ new Set();
13276
16041
  this.unacknowledgedBroadcastAtError = false;
13277
16042
  try {
13278
16043
  this.cachedContext = this.config.viaAgent || this.config.askMode ? await buildMinimalContext(this.vault) : await buildMessageContext(this.vault);
@@ -13317,9 +16082,7 @@ var AgentSession = class {
13317
16082
  // narrates. See cards.ts / backend types.go SupportedSurfaces.
13318
16083
  supported_surfaces: [...CLI_SUPPORTED_SURFACES]
13319
16084
  };
13320
- if (this.config.viaAgent || this.config.askMode) {
13321
- request.via_agent = true;
13322
- }
16085
+ applyAgentMode(request, this.config);
13323
16086
  if (content) {
13324
16087
  request.content = content;
13325
16088
  }
@@ -13349,6 +16112,14 @@ var AgentSession = class {
13349
16112
  }
13350
16113
  },
13351
16114
  onClientSideToolCall: (toolCallId, toolName, input) => {
16115
+ if (toolName === "hl_order") {
16116
+ const orderRef = typeof input.order_ref === "string" ? input.order_ref : "";
16117
+ if (this.firstHlOrderRef === null || this.firstHlOrderRef === void 0) {
16118
+ this.firstHlOrderRef = orderRef;
16119
+ } else if (this.firstHlOrderRef !== orderRef) {
16120
+ return;
16121
+ }
16122
+ }
13352
16123
  const dispatch = dispatchChain.then(() => this.dispatchClientSideTool(toolCallId, toolName, input, ui));
13353
16124
  dispatchChain = dispatch.catch(() => {
13354
16125
  });
@@ -13420,6 +16191,11 @@ var AgentSession = class {
13420
16191
  if (pendingDispatches.length > 0) {
13421
16192
  await Promise.all(pendingDispatches);
13422
16193
  }
16194
+ if (this.terminalHlConfirmation) {
16195
+ this.pendingToolResults = this.pendingToolResults.filter((result) => result.tool !== "hl_order");
16196
+ ui.onDone();
16197
+ return;
16198
+ }
13423
16199
  if (streamResult.disconnected && !streamResult.message) {
13424
16200
  ui.onReconnecting?.();
13425
16201
  await this.recoverDisconnectedTurn(streamResult, callbacks.onBalanceSummary);
@@ -13738,10 +16514,10 @@ var AgentSession = class {
13738
16514
  * by the executor (or a synthetic failure `RecentAction` if the password
13739
16515
  * prompt was declined).
13740
16516
  */
13741
- async runPasswordGatedTool(toolName, toolCallId, ui, body, input) {
16517
+ async runPasswordGatedTool(toolName, toolCallId, ui, body, input, confirmationSummary) {
13742
16518
  let signingRecord;
13743
16519
  if (PASSWORD_REQUIRED_TOOLS.has(toolName)) {
13744
- const summary = (toolName === "sign_tx" ? this.executor.getPendingSummary() : null) ?? `${toolName}${input ? ` ${JSON.stringify(input)}` : ""}`;
16520
+ const summary = confirmationSummary ?? (toolName === "sign_tx" ? this.executor.getPendingSummary() : null) ?? `${toolName}${input ? ` ${JSON.stringify(input)}` : ""}`;
13745
16521
  const approved = await ui.requestConfirmation(summary);
13746
16522
  if (!approved) {
13747
16523
  return reportDeclinedSigning(this.executor, toolName, toolCallId, summary, input, ui);
@@ -13805,6 +16581,51 @@ var AgentSession = class {
13805
16581
  // entries surface as a visible `[cli] unimplemented` warning + failure
13806
16582
  // RecentAction (never silent).
13807
16583
  async dispatchClientSideTool(toolCallId, toolName, input, ui) {
16584
+ if (toolName === "hl_order") {
16585
+ let recent2;
16586
+ try {
16587
+ const conversationId = this.conversationId;
16588
+ if (!conversationId) throw new Error("HL_CONVERSATION_REQUIRED");
16589
+ const orderRef = typeof input.order_ref === "string" ? input.order_ref : "";
16590
+ if (this.firstHlOrderRef === null || this.firstHlOrderRef === void 0) {
16591
+ this.firstHlOrderRef = orderRef;
16592
+ } else if (this.firstHlOrderRef !== orderRef) {
16593
+ return;
16594
+ }
16595
+ const seenRefs = this.seenHlOrderRefs ?? (this.seenHlOrderRefs = /* @__PURE__ */ new Set());
16596
+ if (seenRefs.has(orderRef)) return;
16597
+ seenRefs.add(orderRef);
16598
+ const payload = await this.executor.retrieveHlOrder(this.client, input, conversationId);
16599
+ recent2 = await this.runPasswordGatedTool(
16600
+ toolName,
16601
+ toolCallId,
16602
+ ui,
16603
+ () => this.executor.signAndSubmitHlOrder(this.client, payload),
16604
+ input,
16605
+ formatHlConfirmation(payload)
16606
+ );
16607
+ if (recent2.data?.code === "CONFIRMATION_REQUIRED" /* CONFIRMATION_REQUIRED */) {
16608
+ const proposed = String(recent2.data.proposed ?? formatHlConfirmation(payload));
16609
+ const card = {
16610
+ surface: "hyperliquid_order_confirmation",
16611
+ status: "confirmation_required",
16612
+ order_ref: payload.order_ref,
16613
+ ...payload.summary,
16614
+ proposed
16615
+ };
16616
+ recent2.data.confirmation_card = card;
16617
+ this.terminalHlConfirmation = true;
16618
+ ui.onHlOrderConfirmation?.(card);
16619
+ }
16620
+ } catch (err) {
16621
+ const message = err instanceof Error ? err.message : String(err);
16622
+ recent2 = { tool: toolName, success: false, data: { error: message } };
16623
+ ui.onToolCall(toolCallId, toolName, input);
16624
+ ui.onToolResult(toolCallId, toolName, false, recent2.data, message);
16625
+ }
16626
+ if (!this.terminalHlConfirmation) this.pendingToolResults.push(recent2);
16627
+ return;
16628
+ }
13808
16629
  const handler = CLIENT_SIDE_TOOL_DISPATCH[toolName];
13809
16630
  if (!handler) {
13810
16631
  process.stderr.write(`[cli] unimplemented client-side tool: ${toolName}
@@ -13812,7 +16633,10 @@ var AgentSession = class {
13812
16633
  this.pendingToolResults.push({
13813
16634
  tool: toolName,
13814
16635
  success: false,
13815
- data: { code: "TOOL_UNSUPPORTED" /* TOOL_UNSUPPORTED */, error: `unimplemented in CLI: ${toolName}` }
16636
+ data: {
16637
+ code: "TOOL_UNSUPPORTED" /* TOOL_UNSUPPORTED */,
16638
+ error: `unimplemented in CLI: ${toolName}`
16639
+ }
13816
16640
  });
13817
16641
  return;
13818
16642
  }
@@ -14347,6 +17171,7 @@ function outputAskError(wantsJson, message, code, conversationId, result) {
14347
17171
  if (result?.toolCalls.length) data.tool_calls = result.toolCalls;
14348
17172
  if (result?.response) data.response = result.response;
14349
17173
  if (result?.warnings.length) data.warnings = result.warnings;
17174
+ if (result?.cards.length) data.cards = result.cards;
14350
17175
  if (result?.outcome) data.outcome = result.outcome;
14351
17176
  if (result?.proposedTransaction) {
14352
17177
  data.confirmation_required = true;
@@ -14386,7 +17211,7 @@ var ACK_FAILED_MESSAGE = "A transaction was broadcast, but its post-broadcast re
14386
17211
  function hasCommittedBroadcast(result) {
14387
17212
  return !!result?.transactions.some((tx) => tx.hash.trim().length > 0 && tx.status !== "failed");
14388
17213
  }
14389
- var SIGNING_TOOLS = /* @__PURE__ */ new Set(["sign_tx", "sign_typed_data"]);
17214
+ var SIGNING_TOOLS = /* @__PURE__ */ new Set(["sign_tx", "sign_typed_data", "hl_order"]);
14390
17215
  var CONFIRMATION_REQUIRED_MESSAGE = "The transaction was built but signing was not authorized, so nothing was signed or broadcast. Re-run with --yes to authorize signing.";
14391
17216
  function failedSigningError(result) {
14392
17217
  const failed = [...result.toolCalls].reverse().find((call) => SIGNING_TOOLS.has(call.action));
@@ -14464,9 +17289,15 @@ function outputAskHuman(result, confirmationRequired, proposed) {
14464
17289
  }
14465
17290
  writeSigningRecordLines(result.signingRecords, (line) => process.stdout.write(line));
14466
17291
  for (const card of result.cards) {
14467
- process.stdout.write(`
17292
+ if (card.surface === "balance_summary") {
17293
+ process.stdout.write(`
14468
17294
  ${renderBalanceSummaryCard(card)}
14469
17295
  `);
17296
+ } else {
17297
+ process.stdout.write(`
17298
+ confirmation:${card.proposed}
17299
+ `);
17300
+ }
14470
17301
  }
14471
17302
  for (const card of result.yieldCards) {
14472
17303
  process.stdout.write(`
@@ -14708,7 +17539,7 @@ function formatDate(iso) {
14708
17539
  }
14709
17540
 
14710
17541
  // src/lib/version.ts
14711
- import { getVultisigConfigDir as getVultisigConfigDir3 } from "@vultisig/client-shared";
17542
+ import { getVultisigConfigDir as getVultisigConfigDir4 } from "@vultisig/client-shared";
14712
17543
  import chalk11 from "chalk";
14713
17544
  import { existsSync as existsSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "fs";
14714
17545
  import { join as join4 } from "path";
@@ -14716,7 +17547,7 @@ var cachedVersion = null;
14716
17547
  function getVersion() {
14717
17548
  if (cachedVersion) return cachedVersion;
14718
17549
  if (true) {
14719
- cachedVersion = "4.5.0";
17550
+ cachedVersion = "4.6.0";
14720
17551
  return cachedVersion;
14721
17552
  }
14722
17553
  try {
@@ -14729,7 +17560,7 @@ function getVersion() {
14729
17560
  return cachedVersion;
14730
17561
  }
14731
17562
  }
14732
- var CACHE_DIR = join4(getVultisigConfigDir3(), "cache");
17563
+ var CACHE_DIR = join4(getVultisigConfigDir4(), "cache");
14733
17564
  var VERSION_CACHE_FILE = join4(CACHE_DIR, "version-check.json");
14734
17565
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
14735
17566
  function readVersionCache() {
@@ -14813,7 +17644,7 @@ function formatVersionShort() {
14813
17644
  }
14814
17645
  function formatVersionDetailed() {
14815
17646
  const lines = [];
14816
- const configDir = getVultisigConfigDir3();
17647
+ const configDir = getVultisigConfigDir4();
14817
17648
  lines.push(chalk11.bold(`Vultisig CLI v${getVersion()}`));
14818
17649
  lines.push("");
14819
17650
  lines.push(` Node.js: ${process.version}`);
@@ -15176,7 +18007,7 @@ var EventBuffer = class {
15176
18007
  };
15177
18008
 
15178
18009
  // src/interactive/session.ts
15179
- import { Chain as Chain12, fiatCurrencies as fiatCurrencies3 } from "@vultisig/sdk";
18010
+ import { Chain as Chain13, fiatCurrencies as fiatCurrencies3 } from "@vultisig/sdk";
15180
18011
  import chalk14 from "chalk";
15181
18012
  import ora3 from "ora";
15182
18013
  import * as readline3 from "readline";
@@ -16025,7 +18856,7 @@ Error: ${error2.message}`));
16025
18856
  } else if (rest[i] === "--destination-tag") {
16026
18857
  const tag = rest[i + 1];
16027
18858
  const parsedTag = Number(tag);
16028
- if (chain !== Chain12.Ripple || !/^(0|[1-9]\d*)$/.test(tag ?? "") || !Number.isSafeInteger(parsedTag) || parsedTag > 4294967295) {
18859
+ if (chain !== Chain13.Ripple || !/^(0|[1-9]\d*)$/.test(tag ?? "") || !Number.isSafeInteger(parsedTag) || parsedTag > 4294967295) {
16029
18860
  throw new Error("Invalid XRP DestinationTag: expected an integer from 0 to 4294967295");
16030
18861
  }
16031
18862
  destinationTag = parsedTag;
@@ -16253,7 +19084,7 @@ Error: ${error2.message}`));
16253
19084
  };
16254
19085
 
16255
19086
  // src/lib/completion.ts
16256
- import { getVultisigConfigDir as getVultisigConfigDir4 } from "@vultisig/client-shared";
19087
+ import { getVultisigConfigDir as getVultisigConfigDir5 } from "@vultisig/client-shared";
16257
19088
  import { SUPPORTED_CHAINS as SUPPORTED_CHAINS2 } from "@vultisig/sdk";
16258
19089
  import { program } from "commander";
16259
19090
  import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync5 } from "fs";
@@ -16280,7 +19111,7 @@ function getChains() {
16280
19111
  }
16281
19112
  function getVaultNames() {
16282
19113
  try {
16283
- const vaultDir = getVultisigConfigDir4();
19114
+ const vaultDir = getVultisigConfigDir5();
16284
19115
  if (!existsSync3(vaultDir)) return [];
16285
19116
  const files = readdirSync(vaultDir);
16286
19117
  const names = [];
@@ -16533,10 +19364,10 @@ complete -c vsig -n "__fish_seen_subcommand_from import export" -a "(__fish_comp
16533
19364
  }
16534
19365
 
16535
19366
  // src/lib/config.ts
16536
- import { getVultisigConfigDir as getVultisigConfigDir5 } from "@vultisig/client-shared";
19367
+ import { getVultisigConfigDir as getVultisigConfigDir6 } from "@vultisig/client-shared";
16537
19368
  import { FileStorage } from "@vultisig/sdk/node";
16538
19369
  function getConfigDir() {
16539
- return getVultisigConfigDir5();
19370
+ return getVultisigConfigDir6();
16540
19371
  }
16541
19372
  function createVaultStorage() {
16542
19373
  return new FileStorage({ basePath: getConfigDir() });
@@ -16872,7 +19703,7 @@ See also: balance, tx-status`
16872
19703
  if (!amount && !options.max) throw new Error("Provide an amount or use --max");
16873
19704
  if (amount && options.max) throw new Error("Cannot specify both amount and --max");
16874
19705
  const chain = resolveChainOrThrow(chainStr);
16875
- if (options.destinationTag !== void 0 && chain !== Chain13.Ripple) {
19706
+ if (options.destinationTag !== void 0 && chain !== Chain14.Ripple) {
16876
19707
  throw new Error("--destination-tag is only supported for XRP");
16877
19708
  }
16878
19709
  const destinationTag = options.destinationTag === void 0 ? void 0 : Number(options.destinationTag);