opentool 0.9.0 → 0.10.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
@@ -169,7 +169,10 @@ async function verifyX402Payment(attempt, definition, options = {}) {
169
169
  console.log("[x402] Facilitator /verify response", { status: verifyResponse.status });
170
170
  if (!verifyResponse.ok) {
171
171
  const errorText = await verifyResponse.text().catch(() => "");
172
- console.error("[x402] Facilitator /verify error", { status: verifyResponse.status, body: errorText });
172
+ console.error("[x402] Facilitator /verify error", {
173
+ status: verifyResponse.status,
174
+ body: errorText
175
+ });
173
176
  return {
174
177
  success: false,
175
178
  failure: {
@@ -217,7 +220,10 @@ async function verifyX402Payment(attempt, definition, options = {}) {
217
220
  console.log("[x402] Facilitator /settle response", { status: settleResponse.status });
218
221
  if (!settleResponse.ok) {
219
222
  const errorText = await settleResponse.text().catch(() => "");
220
- console.error("[x402] Facilitator /settle error", { status: settleResponse.status, body: errorText });
223
+ console.error("[x402] Facilitator /settle error", {
224
+ status: settleResponse.status,
225
+ body: errorText
226
+ });
221
227
  return {
222
228
  success: false,
223
229
  failure: {
@@ -235,7 +241,9 @@ async function verifyX402Payment(attempt, definition, options = {}) {
235
241
  });
236
242
  }
237
243
  } catch (error) {
238
- console.error("[x402] Settlement exception", { error: error instanceof Error ? error.message : String(error) });
244
+ console.error("[x402] Settlement exception", {
245
+ error: error instanceof Error ? error.message : String(error)
246
+ });
239
247
  return {
240
248
  success: false,
241
249
  failure: {
@@ -612,7 +620,7 @@ async function payX402WithWallet(walletClient, chainId, request) {
612
620
  }
613
621
 
614
622
  // src/x402/index.ts
615
- var PAYMENT_CONTEXT_SYMBOL = Symbol.for("opentool.x402.context");
623
+ var PAYMENT_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("opentool.x402.context");
616
624
  var X402PaymentRequiredError = class extends Error {
617
625
  constructor(response, verification) {
618
626
  super("X402 Payment required");
@@ -769,23 +777,13 @@ function toDecimalString(value) {
769
777
  }
770
778
 
771
779
  // src/adapters/mcp.ts
772
- var HTTP_METHODS = [
773
- "GET",
774
- "HEAD",
775
- "POST",
776
- "PUT",
777
- "DELETE",
778
- "PATCH",
779
- "OPTIONS"
780
- ];
780
+ var HTTP_METHODS = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
781
781
  function createMcpAdapter(options) {
782
782
  const normalizedSchema = ensureSchema(options.schema);
783
783
  const defaultMethod = resolveDefaultMethod(options);
784
784
  const httpHandler = options.httpHandlers[defaultMethod];
785
785
  if (!httpHandler) {
786
- throw new Error(
787
- `Tool "${options.name}" does not export an HTTP handler for ${defaultMethod}`
788
- );
786
+ throw new Error(`Tool "${options.name}" does not export an HTTP handler for ${defaultMethod}`);
789
787
  }
790
788
  return async function invoke(rawArguments) {
791
789
  const validated = normalizedSchema ? normalizedSchema.parse(rawArguments ?? {}) : rawArguments;
@@ -1017,7 +1015,7 @@ async function loadToolsFromDirectory(metadataMap) {
1017
1015
  target: "jsonSchema7",
1018
1016
  $refStrategy: "none"
1019
1017
  });
1020
- } catch (error) {
1018
+ } catch {
1021
1019
  inputSchema = { type: "object" };
1022
1020
  }
1023
1021
  }
@@ -1189,15 +1187,7 @@ function resolveRuntimePath(value) {
1189
1187
  }
1190
1188
 
1191
1189
  // src/types/index.ts
1192
- var HTTP_METHODS2 = [
1193
- "GET",
1194
- "HEAD",
1195
- "POST",
1196
- "PUT",
1197
- "DELETE",
1198
- "PATCH",
1199
- "OPTIONS"
1200
- ];
1190
+ var HTTP_METHODS2 = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
1201
1191
  var BASE_ALCHEMY_HOST = "https://base-mainnet.g.alchemy.com/v2/";
1202
1192
  var ETHEREUM_ALCHEMY_HOST = "https://eth-mainnet.g.alchemy.com/v2/";
1203
1193
  var BASE_SEPOLIA_ALCHEMY_HOST = "https://base-sepolia.g.alchemy.com/v2/";
@@ -1233,10 +1223,7 @@ var chains = {
1233
1223
  slug: "ethereum",
1234
1224
  name: "Ethereum",
1235
1225
  chain: mainnet,
1236
- rpcUrl: buildRpcResolver(
1237
- ETHEREUM_ALCHEMY_HOST,
1238
- mainnet.rpcUrls.default.http
1239
- ),
1226
+ rpcUrl: buildRpcResolver(ETHEREUM_ALCHEMY_HOST, mainnet.rpcUrls.default.http),
1240
1227
  publicRpcUrls: mainnet.rpcUrls.default.http
1241
1228
  },
1242
1229
  baseSepolia: {
@@ -1244,20 +1231,14 @@ var chains = {
1244
1231
  slug: "base-sepolia",
1245
1232
  name: "Base Sepolia",
1246
1233
  chain: baseSepolia,
1247
- rpcUrl: buildRpcResolver(
1248
- BASE_SEPOLIA_ALCHEMY_HOST,
1249
- baseSepolia.rpcUrls.default.http
1250
- )
1234
+ rpcUrl: buildRpcResolver(BASE_SEPOLIA_ALCHEMY_HOST, baseSepolia.rpcUrls.default.http)
1251
1235
  },
1252
1236
  arbitrum: {
1253
1237
  id: arbitrum.id,
1254
1238
  slug: "arbitrum",
1255
1239
  name: "Arbitrum One",
1256
1240
  chain: arbitrum,
1257
- rpcUrl: buildRpcResolver(
1258
- ARBITRUM_ALCHEMY_HOST,
1259
- arbitrum.rpcUrls.default.http
1260
- ),
1241
+ rpcUrl: buildRpcResolver(ARBITRUM_ALCHEMY_HOST, arbitrum.rpcUrls.default.http),
1261
1242
  publicRpcUrls: arbitrum.rpcUrls.default.http
1262
1243
  },
1263
1244
  arbitrumSepolia: {
@@ -1265,10 +1246,7 @@ var chains = {
1265
1246
  slug: "arbitrum-sepolia",
1266
1247
  name: "Arbitrum Sepolia",
1267
1248
  chain: arbitrumSepolia,
1268
- rpcUrl: buildRpcResolver(
1269
- ARBITRUM_SEPOLIA_ALCHEMY_HOST,
1270
- arbitrumSepolia.rpcUrls.default.http
1271
- ),
1249
+ rpcUrl: buildRpcResolver(ARBITRUM_SEPOLIA_ALCHEMY_HOST, arbitrumSepolia.rpcUrls.default.http),
1272
1250
  publicRpcUrls: arbitrumSepolia.rpcUrls.default.http
1273
1251
  }
1274
1252
  };
@@ -1296,33 +1274,15 @@ function token(chainId, symbol, name, address, decimals) {
1296
1274
  var tokens = {
1297
1275
  base: {
1298
1276
  ...createNativeToken(base.id, "ETH", "Ether"),
1299
- USDC: token(
1300
- base.id,
1301
- "USDC",
1302
- "USD Coin",
1303
- "0x833589fCD6eDb6E08f4c7C31c9A8Ba32D74b86B2",
1304
- 6
1305
- )
1277
+ USDC: token(base.id, "USDC", "USD Coin", "0x833589fCD6eDb6E08f4c7C31c9A8Ba32D74b86B2", 6)
1306
1278
  },
1307
1279
  ethereum: {
1308
1280
  ...createNativeToken(mainnet.id, "ETH", "Ether"),
1309
- USDC: token(
1310
- mainnet.id,
1311
- "USDC",
1312
- "USD Coin",
1313
- "0xA0b86991c6218b36c1d19d4a2e9Eb0cE3606eB48",
1314
- 6
1315
- )
1281
+ USDC: token(mainnet.id, "USDC", "USD Coin", "0xA0b86991c6218b36c1d19d4a2e9Eb0cE3606eB48", 6)
1316
1282
  },
1317
1283
  arbitrum: {
1318
1284
  ...createNativeToken(arbitrum.id, "ETH", "Ether"),
1319
- USDC: token(
1320
- arbitrum.id,
1321
- "USDC",
1322
- "USD Coin",
1323
- "0xaf88d065e77c8cc2239327c5edb3a432268e5831",
1324
- 6
1325
- )
1285
+ USDC: token(arbitrum.id, "USDC", "USD Coin", "0xaf88d065e77c8cc2239327c5edb3a432268e5831", 6)
1326
1286
  },
1327
1287
  arbitrumSepolia: {
1328
1288
  ...createNativeToken(arbitrumSepolia.id, "ETH", "Ether"),
@@ -1626,11 +1586,7 @@ var walletToolkit = {
1626
1586
  };
1627
1587
 
1628
1588
  // src/store/index.ts
1629
- var STORE_EVENT_LEVELS = [
1630
- "decision",
1631
- "execution",
1632
- "lifecycle"
1633
- ];
1589
+ var STORE_EVENT_LEVELS = ["decision", "execution", "lifecycle"];
1634
1590
  var STORE_EVENT_LEVEL_SET = new Set(STORE_EVENT_LEVELS);
1635
1591
  var MARKET_REQUIRED_ACTIONS = [
1636
1592
  "swap",
@@ -1697,7 +1653,7 @@ var resolveEventLevel = (input) => {
1697
1653
  return null;
1698
1654
  };
1699
1655
  var normalizeStoreInput = (input) => {
1700
- const metadata = { ...input.metadata ?? {} };
1656
+ const metadata = { ...input.metadata };
1701
1657
  const eventLevel = resolveEventLevel({ ...input, metadata });
1702
1658
  if (eventLevel) {
1703
1659
  metadata.eventLevel = eventLevel;
@@ -1716,9 +1672,7 @@ function resolveConfig(options) {
1716
1672
  throw new StoreError("BASE_URL is required to store activity events");
1717
1673
  }
1718
1674
  if (!apiKey) {
1719
- throw new StoreError(
1720
- "OPENPOND_API_KEY is required to store activity events"
1721
- );
1675
+ throw new StoreError("OPENPOND_API_KEY is required to store activity events");
1722
1676
  }
1723
1677
  const normalizedBaseUrl = baseUrl.replace(/\/$/, "");
1724
1678
  const fetchFn = options?.fetchFn ?? globalThis.fetch;
@@ -1734,7 +1688,7 @@ async function requestJson(url, options, init) {
1734
1688
  headers: {
1735
1689
  "content-type": "application/json",
1736
1690
  "openpond-api-key": apiKey,
1737
- ...init.headers ?? {}
1691
+ ...init.headers
1738
1692
  }
1739
1693
  });
1740
1694
  if (!response.ok) {
@@ -1744,11 +1698,7 @@ async function requestJson(url, options, init) {
1744
1698
  } catch {
1745
1699
  body = await response.text().catch(() => void 0);
1746
1700
  }
1747
- throw new StoreError(
1748
- `Request failed with status ${response.status}`,
1749
- response.status,
1750
- body
1751
- );
1701
+ throw new StoreError(`Request failed with status ${response.status}`, response.status, body);
1752
1702
  }
1753
1703
  if (response.status === 204) {
1754
1704
  return null;
@@ -1765,15 +1715,11 @@ async function store(input, options) {
1765
1715
  const eventLevel = normalizedInput.eventLevel;
1766
1716
  const normalizedAction = normalizeAction(normalizedInput.action);
1767
1717
  if (mode === "backtest" && !normalizedInput.backtestRunId) {
1768
- throw new StoreError(
1769
- `backtestRunId is required when mode is "backtest"`
1770
- );
1718
+ throw new StoreError(`backtestRunId is required when mode is "backtest"`);
1771
1719
  }
1772
1720
  if (eventLevel === "execution" || eventLevel === "lifecycle") {
1773
1721
  if (!normalizedAction || !EXECUTION_ACTIONS_SET.has(normalizedAction)) {
1774
- throw new StoreError(
1775
- `eventLevel "${eventLevel}" requires an execution action`
1776
- );
1722
+ throw new StoreError(`eventLevel "${eventLevel}" requires an execution action`);
1777
1723
  }
1778
1724
  }
1779
1725
  if (eventLevel === "execution" && !hasMarketIdentity(normalizedInput.market)) {
@@ -2103,9 +2049,7 @@ async function getUniverse(args) {
2103
2049
  const response = await args.fetcher(`${args.baseUrl}/info`, {
2104
2050
  method: "POST",
2105
2051
  headers: { "content-type": "application/json" },
2106
- body: JSON.stringify(
2107
- dexKey ? { type: "meta", dex: dexKey } : { type: "meta" }
2108
- )
2052
+ body: JSON.stringify(dexKey ? { type: "meta", dex: dexKey } : { type: "meta" })
2109
2053
  });
2110
2054
  const json = await response.json().catch(() => null);
2111
2055
  if (!response.ok || !json?.universe) {
@@ -2143,9 +2087,7 @@ async function getSpotMeta(args) {
2143
2087
  function resolveAssetIndex(symbol, universe) {
2144
2088
  const [raw] = symbol.split("-");
2145
2089
  const target = raw.trim();
2146
- const index = universe.findIndex(
2147
- (entry) => entry.name.toUpperCase() === target.toUpperCase()
2148
- );
2090
+ const index = universe.findIndex((entry) => entry.name.toUpperCase() === target.toUpperCase());
2149
2091
  if (index === -1) {
2150
2092
  throw new Error(`Unknown Hyperliquid asset symbol: ${symbol}`);
2151
2093
  }
@@ -2175,9 +2117,7 @@ async function getPerpDexs(args) {
2175
2117
  async function resolveDexIndex(args) {
2176
2118
  const dexs = await getPerpDexs(args);
2177
2119
  const target = args.dex.trim().toLowerCase();
2178
- const index = dexs.findIndex(
2179
- (entry) => entry?.name?.toLowerCase() === target
2180
- );
2120
+ const index = dexs.findIndex((entry) => entry?.name?.toLowerCase() === target);
2181
2121
  if (index === -1) {
2182
2122
  throw new Error(`Unknown Hyperliquid perp dex: ${args.dex}`);
2183
2123
  }
@@ -2364,15 +2304,7 @@ async function signL1Action(args) {
2364
2304
  return splitSignature(signatureHex);
2365
2305
  }
2366
2306
  async function signSpotSend(args) {
2367
- const {
2368
- wallet: wallet2,
2369
- hyperliquidChain,
2370
- signatureChainId,
2371
- destination,
2372
- token: token2,
2373
- amount,
2374
- time
2375
- } = args;
2307
+ const { wallet: wallet2, hyperliquidChain, signatureChainId, destination, token: token2, amount, time } = args;
2376
2308
  const domain = {
2377
2309
  name: "HyperliquidSignTransaction",
2378
2310
  version: "1",
@@ -2781,9 +2713,7 @@ var HyperliquidExchangeClient = class {
2781
2713
  this.expiresAfter = args.expiresAfter;
2782
2714
  const resolvedNonceSource = args.walletNonceProvider ?? args.wallet.nonceSource ?? args.nonceSource;
2783
2715
  if (!resolvedNonceSource) {
2784
- throw new Error(
2785
- "Wallet nonce source is required for Hyperliquid exchange actions."
2786
- );
2716
+ throw new Error("Wallet nonce source is required for Hyperliquid exchange actions.");
2787
2717
  }
2788
2718
  this.nonceSource = resolvedNonceSource;
2789
2719
  }
@@ -2913,9 +2843,7 @@ var HyperliquidExchangeClient = class {
2913
2843
  expiresAfter: this.expiresAfter,
2914
2844
  nonceSource: this.nonceSource
2915
2845
  };
2916
- return setHyperliquidDexAbstraction(
2917
- params.user ? { ...base2, user: params.user } : base2
2918
- );
2846
+ return setHyperliquidDexAbstraction(params.user ? { ...base2, user: params.user } : base2);
2919
2847
  }
2920
2848
  setAccountAbstractionMode(params) {
2921
2849
  const base2 = {
@@ -2939,24 +2867,18 @@ var HyperliquidExchangeClient = class {
2939
2867
  expiresAfter: this.expiresAfter,
2940
2868
  nonceSource: this.nonceSource
2941
2869
  };
2942
- return setHyperliquidPortfolioMargin(
2943
- params.user ? { ...base2, user: params.user } : base2
2944
- );
2870
+ return setHyperliquidPortfolioMargin(params.user ? { ...base2, user: params.user } : base2);
2945
2871
  }
2946
2872
  };
2947
2873
  async function setHyperliquidPortfolioMargin(options) {
2948
2874
  const env = options.environment ?? "mainnet";
2949
2875
  if (!options.wallet?.account || !options.wallet.walletClient) {
2950
- throw new Error(
2951
- "Wallet with signing capability is required for portfolio margin."
2952
- );
2876
+ throw new Error("Wallet with signing capability is required for portfolio margin.");
2953
2877
  }
2954
2878
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
2955
2879
  const signatureChainId = getSignatureChainId(env);
2956
2880
  const hyperliquidChain = HL_CHAIN_LABEL[env];
2957
- const user = normalizeAddress(
2958
- options.user ?? options.wallet.address
2959
- );
2881
+ const user = normalizeAddress(options.user ?? options.wallet.address);
2960
2882
  const action = {
2961
2883
  type: "userPortfolioMargin",
2962
2884
  enabled: Boolean(options.enabled),
@@ -2985,16 +2907,12 @@ async function setHyperliquidPortfolioMargin(options) {
2985
2907
  async function setHyperliquidDexAbstraction(options) {
2986
2908
  const env = options.environment ?? "mainnet";
2987
2909
  if (!options.wallet?.account || !options.wallet.walletClient) {
2988
- throw new Error(
2989
- "Wallet with signing capability is required for dex abstraction."
2990
- );
2910
+ throw new Error("Wallet with signing capability is required for dex abstraction.");
2991
2911
  }
2992
2912
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
2993
2913
  const signatureChainId = getSignatureChainId(env);
2994
2914
  const hyperliquidChain = HL_CHAIN_LABEL[env];
2995
- const user = normalizeAddress(
2996
- options.user ?? options.wallet.address
2997
- );
2915
+ const user = normalizeAddress(options.user ?? options.wallet.address);
2998
2916
  const action = {
2999
2917
  type: "userDexAbstraction",
3000
2918
  enabled: Boolean(options.enabled),
@@ -3023,16 +2941,12 @@ async function setHyperliquidDexAbstraction(options) {
3023
2941
  async function setHyperliquidAccountAbstractionMode(options) {
3024
2942
  const env = options.environment ?? "mainnet";
3025
2943
  if (!options.wallet?.account || !options.wallet.walletClient) {
3026
- throw new Error(
3027
- "Wallet with signing capability is required for account abstraction mode."
3028
- );
2944
+ throw new Error("Wallet with signing capability is required for account abstraction mode.");
3029
2945
  }
3030
2946
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
3031
2947
  const signatureChainId = getSignatureChainId(env);
3032
2948
  const hyperliquidChain = HL_CHAIN_LABEL[env];
3033
- const user = normalizeAddress(
3034
- options.user ?? options.wallet.address
3035
- );
2949
+ const user = normalizeAddress(options.user ?? options.wallet.address);
3036
2950
  const abstraction = resolveHyperliquidAbstractionFromMode(options.mode);
3037
2951
  const action = {
3038
2952
  type: "userSetAbstraction",
@@ -3074,14 +2988,10 @@ async function cancelHyperliquidOrdersByCloid(options) {
3074
2988
  options.cancels.forEach((c) => assertSymbol(c.symbol));
3075
2989
  const action = {
3076
2990
  type: "cancelByCloid",
3077
- cancels: await withAssetIndexes(
3078
- options,
3079
- options.cancels,
3080
- (idx, entry) => ({
3081
- asset: idx,
3082
- cloid: normalizeCloid(entry.cloid)
3083
- })
3084
- )
2991
+ cancels: await withAssetIndexes(options, options.cancels, (idx, entry) => ({
2992
+ asset: idx,
2993
+ cloid: normalizeCloid(entry.cloid)
2994
+ }))
3085
2995
  };
3086
2996
  return submitExchangeAction(options, action);
3087
2997
  }
@@ -4032,10 +3942,7 @@ function formatScaledInt(value, decimals) {
4032
3942
  return `${negative ? "-" : ""}${integer.toString()}`;
4033
3943
  }
4034
3944
  const fractionStr = fraction.toString().padStart(decimals, "0");
4035
- return `${negative ? "-" : ""}${integer.toString()}.${fractionStr}`.replace(
4036
- /\.?0+$/,
4037
- ""
4038
- );
3945
+ return `${negative ? "-" : ""}${integer.toString()}.${fractionStr}`.replace(/\.?0+$/, "");
4039
3946
  }
4040
3947
  function resolveSpotSizeDecimals(meta, symbol) {
4041
3948
  const universe = meta.universe ?? [];
@@ -4143,10 +4050,7 @@ async function fetchHyperliquidSpotTickSize(params) {
4143
4050
  if (!Number.isFinite(params.marketIndex)) {
4144
4051
  throw new Error("Hyperliquid spot market index is invalid.");
4145
4052
  }
4146
- return fetchHyperliquidTickSizeForCoin(
4147
- params.environment,
4148
- `@${params.marketIndex}`
4149
- );
4053
+ return fetchHyperliquidTickSizeForCoin(params.environment, `@${params.marketIndex}`);
4150
4054
  }
4151
4055
  async function fetchHyperliquidTickSizeForCoin(environment, coin) {
4152
4056
  const base2 = API_BASES[environment];
@@ -4160,9 +4064,7 @@ async function fetchHyperliquidTickSizeForCoin(environment, coin) {
4160
4064
  }
4161
4065
  const data = await res.json().catch(() => null);
4162
4066
  const levels = Array.isArray(data?.levels) ? data?.levels ?? [] : [];
4163
- const prices = levels.flatMap(
4164
- (side) => Array.isArray(side) ? side.map((entry) => String(entry?.px ?? "")) : []
4165
- ).filter((px) => px.length > 0);
4067
+ const prices = levels.flatMap((side) => Array.isArray(side) ? side.map((entry) => String(entry?.px ?? "")) : []).filter((px) => px.length > 0);
4166
4068
  if (prices.length < 2) {
4167
4069
  throw new Error(`Hyperliquid l2Book missing price levels for ${coin}`);
4168
4070
  }
@@ -4253,9 +4155,7 @@ async function fetchHyperliquidSpotMarketInfo(params) {
4253
4155
  price = readHyperliquidNumber(ctx?.markPx ?? ctx?.midPx ?? ctx?.oraclePx);
4254
4156
  }
4255
4157
  if (!price || price <= 0) {
4256
- throw new Error(
4257
- `No spot price available for ${normalizedBase}/${normalizedQuote}`
4258
- );
4158
+ throw new Error(`No spot price available for ${normalizedBase}/${normalizedQuote}`);
4259
4159
  }
4260
4160
  const marketIndex = typeof market?.index === "number" ? market.index : idx;
4261
4161
  return {
@@ -4405,9 +4305,7 @@ async function placeHyperliquidOrder(options) {
4405
4305
  } = options;
4406
4306
  const effectiveBuilder = BUILDER_CODE;
4407
4307
  if (!wallet2?.account || !wallet2.walletClient) {
4408
- throw new Error(
4409
- "Hyperliquid order signing requires a wallet with signing capabilities."
4410
- );
4308
+ throw new Error("Hyperliquid order signing requires a wallet with signing capabilities.");
4411
4309
  }
4412
4310
  if (!orders.length) {
4413
4311
  throw new Error("At least one order is required.");
@@ -4521,10 +4419,7 @@ async function placeHyperliquidOrder(options) {
4521
4419
  );
4522
4420
  if (errorStatuses.length) {
4523
4421
  const message = errorStatuses.map((entry) => entry.error).join(", ");
4524
- throw new HyperliquidApiError(
4525
- message || "Hyperliquid rejected the order.",
4526
- json
4527
- );
4422
+ throw new HyperliquidApiError(message || "Hyperliquid rejected the order.", json);
4528
4423
  }
4529
4424
  return json;
4530
4425
  }
@@ -4544,9 +4439,7 @@ async function depositToHyperliquidBridge(options) {
4544
4439
  const usdcAddress = getUsdcAddress(environment);
4545
4440
  const amountUnits = parseUnits(amount, 6);
4546
4441
  if (!wallet2.walletClient || !wallet2.publicClient) {
4547
- throw new Error(
4548
- "Wallet client and public client are required for deposit."
4549
- );
4442
+ throw new Error("Wallet client and public client are required for deposit.");
4550
4443
  }
4551
4444
  const walletClient = wallet2.walletClient;
4552
4445
  const publicClient = wallet2.publicClient;
@@ -4571,15 +4464,10 @@ async function depositToHyperliquidBridge(options) {
4571
4464
  }
4572
4465
  async function withdrawFromHyperliquid(options) {
4573
4466
  const { environment, amount, destination, wallet: wallet2 } = options;
4574
- const normalizedAmount = normalizePositiveDecimalString(
4575
- amount,
4576
- "Withdraw amount"
4577
- );
4467
+ const normalizedAmount = normalizePositiveDecimalString(amount, "Withdraw amount");
4578
4468
  const parsedAmount = Number.parseFloat(normalizedAmount);
4579
4469
  if (!wallet2.account || !wallet2.walletClient || !wallet2.publicClient) {
4580
- throw new Error(
4581
- "Wallet client and public client are required for withdraw."
4582
- );
4470
+ throw new Error("Wallet client and public client are required for withdraw.");
4583
4471
  }
4584
4472
  const signatureChainId = getSignatureChainId(environment);
4585
4473
  const hyperliquidChain = HL_CHAIN_LABEL[environment];
@@ -4662,9 +4550,7 @@ async function fetchHyperliquidClearinghouseState(params) {
4662
4550
  async function approveHyperliquidBuilderFee(options) {
4663
4551
  const { environment, wallet: wallet2, nonce, signatureChainId } = options;
4664
4552
  if (!wallet2?.account || !wallet2.walletClient) {
4665
- throw new Error(
4666
- "Hyperliquid builder approval requires a wallet with signing capabilities."
4667
- );
4553
+ throw new Error("Hyperliquid builder approval requires a wallet with signing capabilities.");
4668
4554
  }
4669
4555
  const maxFeeRateValue = BUILDER_CODE.fee / 1e3;
4670
4556
  const formattedPercent = `${maxFeeRateValue}%`;
@@ -4887,9 +4773,7 @@ function normalizeStringArrayish(value) {
4887
4773
  return normalizeArrayish(value).map((entry) => entry == null ? "" : String(entry).trim()).filter((entry) => entry.length > 0);
4888
4774
  }
4889
4775
  function normalizeNumberArrayish(value) {
4890
- return normalizeArrayish(value).map(
4891
- (entry) => typeof entry === "number" ? entry : Number.parseFloat(String(entry))
4892
- ).filter((entry) => Number.isFinite(entry));
4776
+ return normalizeArrayish(value).map((entry) => typeof entry === "number" ? entry : Number.parseFloat(String(entry))).filter((entry) => Number.isFinite(entry));
4893
4777
  }
4894
4778
  function normalizeTags(value) {
4895
4779
  if (!Array.isArray(value)) return [];
@@ -5533,9 +5417,7 @@ async function fetchPolymarketMarkets(params = {}) {
5533
5417
  if (params.slug) url.searchParams.set("slug", params.slug);
5534
5418
  const data = await requestJson3(url.toString());
5535
5419
  const markets = data.flatMap(
5536
- (event) => Array.isArray(event?.markets) ? event.markets.map(
5537
- (market) => normalizeGammaMarket(market, event)
5538
- ) : []
5420
+ (event) => Array.isArray(event?.markets) ? event.markets.map((market) => normalizeGammaMarket(market, event)) : []
5539
5421
  );
5540
5422
  const filtered = params.category ? markets.filter(
5541
5423
  (market) => (market.category ?? "").toLowerCase().includes(params.category.toLowerCase())
@@ -5886,9 +5768,7 @@ function ensureTextContent(message, options) {
5886
5768
  if (flattened !== void 0) {
5887
5769
  return flattened;
5888
5770
  }
5889
- throw new AIError(
5890
- options?.errorMessage ?? "Assistant response did not contain textual content."
5891
- );
5771
+ throw new AIError(options?.errorMessage ?? "Assistant response did not contain textual content.");
5892
5772
  }
5893
5773
  function extractTextPart(part, options) {
5894
5774
  if (!part || typeof part !== "object") {
@@ -6120,7 +6000,7 @@ async function streamText(options, clientConfig = {}) {
6120
6000
  } finally {
6121
6001
  try {
6122
6002
  reader.releaseLock();
6123
- } catch (error) {
6003
+ } catch {
6124
6004
  }
6125
6005
  abortBundle.cleanup();
6126
6006
  }
@@ -6255,11 +6135,7 @@ function buildRequestPayload(options, model, capabilities, metadataExtras) {
6255
6135
  assignIfDefined(payload, "top_p", generation.topP);
6256
6136
  assignIfDefined(payload, "max_tokens", generation.maxTokens);
6257
6137
  assignIfDefined(payload, "stop", generation.stop);
6258
- assignIfDefined(
6259
- payload,
6260
- "frequency_penalty",
6261
- generation.frequencyPenalty
6262
- );
6138
+ assignIfDefined(payload, "frequency_penalty", generation.frequencyPenalty);
6263
6139
  assignIfDefined(payload, "presence_penalty", generation.presencePenalty);
6264
6140
  assignIfDefined(payload, "response_format", generation.responseFormat);
6265
6141
  const toolExecution = options.toolExecution;
@@ -6271,11 +6147,7 @@ function buildRequestPayload(options, model, capabilities, metadataExtras) {
6271
6147
  } else if (options.toolChoice && options.toolChoice !== "none") {
6272
6148
  payload.tool_choice = "none";
6273
6149
  }
6274
- const metadataPayload = buildMetadataPayload(
6275
- options.metadata,
6276
- toolExecution,
6277
- metadataExtras
6278
- );
6150
+ const metadataPayload = buildMetadataPayload(options.metadata, toolExecution, metadataExtras);
6279
6151
  if (metadataPayload) {
6280
6152
  payload.metadata = metadataPayload;
6281
6153
  }
@@ -6299,9 +6171,7 @@ function createAbortBundle(upstreamSignal, timeoutMs) {
6299
6171
  } else {
6300
6172
  const onAbort = () => controller.abort(upstreamSignal.reason);
6301
6173
  upstreamSignal.addEventListener("abort", onAbort, { once: true });
6302
- cleanupCallbacks.push(
6303
- () => upstreamSignal.removeEventListener("abort", onAbort)
6304
- );
6174
+ cleanupCallbacks.push(() => upstreamSignal.removeEventListener("abort", onAbort));
6305
6175
  }
6306
6176
  }
6307
6177
  if (timeoutMs && timeoutMs > 0) {
@@ -6333,11 +6203,9 @@ function buildMetadataPayload(base2, toolExecution, extras) {
6333
6203
  continue;
6334
6204
  }
6335
6205
  if (key === "openpond" && typeof value === "object" && value !== null) {
6336
- const existing = {
6337
- ...metadata.openpond ?? {}
6338
- };
6206
+ const existing = metadata.openpond;
6339
6207
  metadata.openpond = {
6340
- ...existing,
6208
+ ...typeof existing === "object" && existing !== null ? existing : void 0,
6341
6209
  ...value
6342
6210
  };
6343
6211
  } else {
@@ -6346,8 +6214,9 @@ function buildMetadataPayload(base2, toolExecution, extras) {
6346
6214
  }
6347
6215
  }
6348
6216
  if (toolExecution) {
6217
+ const existing = metadata.openpond;
6349
6218
  const openpond = {
6350
- ...metadata.openpond ?? {},
6219
+ ...typeof existing === "object" && existing !== null ? existing : void 0,
6351
6220
  toolExecution
6352
6221
  };
6353
6222
  metadata.openpond = openpond;
@@ -6481,10 +6350,7 @@ var X402PaymentSchema = z.object({
6481
6350
  }),
6482
6351
  metadata: z.record(z.string(), z.unknown()).optional()
6483
6352
  }).passthrough();
6484
- var PaymentConfigSchema = z.union([
6485
- X402PaymentSchema,
6486
- z.record(z.string(), z.unknown())
6487
- ]);
6353
+ var PaymentConfigSchema = z.union([X402PaymentSchema, z.record(z.string(), z.unknown())]);
6488
6354
  var DiscoveryMetadataSchema = z.object({
6489
6355
  keywords: z.array(z.string()).optional(),
6490
6356
  category: z.string().optional(),
@@ -6882,7 +6748,7 @@ function buildDiscovery(authored) {
6882
6748
  }
6883
6749
  const merged = {
6884
6750
  ...legacyDiscovery,
6885
- ...authored.discovery ?? {}
6751
+ ...authored.discovery
6886
6752
  };
6887
6753
  return Object.keys(merged).length > 0 ? merged : void 0;
6888
6754
  }
@@ -6898,7 +6764,9 @@ function normalizeScheduleExpression(raw, context) {
6898
6764
  const cronBody = extractCronBody(value);
6899
6765
  const cronFields = cronBody.trim().split(/\s+/).filter(Boolean);
6900
6766
  if (cronFields.length !== 5 && cronFields.length !== 6) {
6901
- throw new Error(`${context}: cron expression must have 5 or 6 fields (got ${cronFields.length})`);
6767
+ throw new Error(
6768
+ `${context}: cron expression must have 5 or 6 fields (got ${cronFields.length})`
6769
+ );
6902
6770
  }
6903
6771
  validateCronTokens(cronFields, context);
6904
6772
  return {
@@ -6922,14 +6790,7 @@ function validateCronTokens(fields, context) {
6922
6790
  }
6923
6791
 
6924
6792
  // src/cli/validate.ts
6925
- var SUPPORTED_EXTENSIONS = [
6926
- ".ts",
6927
- ".tsx",
6928
- ".js",
6929
- ".jsx",
6930
- ".mjs",
6931
- ".cjs"
6932
- ];
6793
+ var SUPPORTED_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
6933
6794
  var MIN_TEMPLATE_CONFIG_VERSION = 2;
6934
6795
  var TEMPLATE_PREVIEW_TITLE_MAX = 80;
6935
6796
  var TEMPLATE_PREVIEW_SUBTITLE_MAX = 120;
@@ -6999,14 +6860,10 @@ function normalizeTemplatePreview(value, file, toolName, requirePreview) {
6999
6860
  required: true,
7000
6861
  max: TEMPLATE_PREVIEW_SUBTITLE_MAX
7001
6862
  });
7002
- const description = parseNonEmptyString(
7003
- record.description,
7004
- `${pathPrefix}.description`,
7005
- {
7006
- required: true,
7007
- max: TEMPLATE_PREVIEW_DESCRIPTION_MAX
7008
- }
7009
- );
6863
+ const description = parseNonEmptyString(record.description, `${pathPrefix}.description`, {
6864
+ required: true,
6865
+ max: TEMPLATE_PREVIEW_DESCRIPTION_MAX
6866
+ });
7010
6867
  const descriptionLineCount = description.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).length;
7011
6868
  if (descriptionLineCount < TEMPLATE_PREVIEW_MIN_LINES || descriptionLineCount > TEMPLATE_PREVIEW_MAX_LINES) {
7012
6869
  throw new Error(
@@ -7099,15 +6956,13 @@ async function loadAndValidateTools(toolsDir, options = {}) {
7099
6956
  const profileRaw = toolModule?.profile && typeof toolModule.profile === "object" ? toolModule.profile : null;
7100
6957
  const schedule = profileRaw?.schedule ?? null;
7101
6958
  const profileNotifyEmail = typeof profileRaw?.notifyEmail === "boolean" ? profileRaw.notifyEmail : void 0;
7102
- const allowedProfileCategories = [
7103
- "strategy",
7104
- "tracker",
7105
- "orchestrator"
7106
- ];
6959
+ const allowedProfileCategories = ["strategy", "tracker", "orchestrator"];
7107
6960
  const profileCategoryCandidate = typeof profileRaw?.category === "string" ? profileRaw.category : void 0;
7108
6961
  let profileCategoryRaw;
7109
6962
  if (profileCategoryCandidate !== void 0) {
7110
- const isAllowed = allowedProfileCategories.includes(profileCategoryCandidate);
6963
+ const isAllowed = allowedProfileCategories.includes(
6964
+ profileCategoryCandidate
6965
+ );
7111
6966
  if (!isAllowed) {
7112
6967
  throw new Error(
7113
6968
  `${file}: profile.category must be one of ${allowedProfileCategories.join(", ")}`
@@ -7122,22 +6977,16 @@ async function loadAndValidateTools(toolsDir, options = {}) {
7122
6977
  }
7123
6978
  profileAssetsRaw.forEach((entry, index) => {
7124
6979
  if (!entry || typeof entry !== "object") {
7125
- throw new Error(
7126
- `${file}: profile.assets[${index}] must be an object.`
7127
- );
6980
+ throw new Error(`${file}: profile.assets[${index}] must be an object.`);
7128
6981
  }
7129
6982
  const record = entry;
7130
6983
  const venue = typeof record.venue === "string" ? record.venue.trim() : "";
7131
6984
  if (!venue) {
7132
- throw new Error(
7133
- `${file}: profile.assets[${index}].venue must be a non-empty string.`
7134
- );
6985
+ throw new Error(`${file}: profile.assets[${index}].venue must be a non-empty string.`);
7135
6986
  }
7136
6987
  const chain = record.chain;
7137
6988
  if (typeof chain !== "string" && typeof chain !== "number") {
7138
- throw new Error(
7139
- `${file}: profile.assets[${index}].chain must be a string or number.`
7140
- );
6989
+ throw new Error(`${file}: profile.assets[${index}].chain must be a string or number.`);
7141
6990
  }
7142
6991
  const symbols = record.assetSymbols;
7143
6992
  if (!Array.isArray(symbols) || symbols.length === 0) {
@@ -7231,14 +7080,14 @@ async function loadAndValidateTools(toolsDir, options = {}) {
7231
7080
  throw new Error(`${file}: POST tools must export a Zod schema as 'schema'`);
7232
7081
  }
7233
7082
  if (schedule && typeof schedule.cron === "string") {
7234
- throw new Error(`${file}: POST tools must not define profile.schedule; use GET + cron for scheduled tasks.`);
7083
+ throw new Error(
7084
+ `${file}: POST tools must not define profile.schedule; use GET + cron for scheduled tasks.`
7085
+ );
7235
7086
  }
7236
7087
  }
7237
7088
  const httpHandlers = [...httpHandlersRaw];
7238
7089
  if (httpHandlers.length === 0) {
7239
- throw new Error(
7240
- `${file} must export at least one HTTP handler (e.g. POST)`
7241
- );
7090
+ throw new Error(`${file} must export at least one HTTP handler (e.g. POST)`);
7242
7091
  }
7243
7092
  if (paymentExport) {
7244
7093
  for (let index = 0; index < httpHandlers.length; index += 1) {
@@ -7264,7 +7113,7 @@ async function loadAndValidateTools(toolsDir, options = {}) {
7264
7113
  ...metadataOverrides,
7265
7114
  payment: metadataOverrides.payment ?? paymentExport,
7266
7115
  annotations: {
7267
- ...metadataOverrides.annotations ?? {},
7116
+ ...metadataOverrides.annotations,
7268
7117
  requiresPayment: metadataOverrides.annotations?.requiresPayment ?? true
7269
7118
  }
7270
7119
  };