opentool 0.8.22 → 0.8.24

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.d.ts CHANGED
@@ -7,7 +7,7 @@ export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, HyperliquidAbstraction, Hyperl
7
7
  import { c as WalletFullContext } from './types-BVLpaY4O.js';
8
8
  export { C as ChainMetadata, i as ChainReference, a as ChainTokenMap, H as Hex, g as HexAddress, R as RpcProviderOptions, h as RpcUrlResolver, T as TokenMetadata, l as TurnkeyOptions, k as TurnkeySignWith, r as WalletBaseContext, s as WalletContext, n as WalletOptions, m as WalletOptionsBase, b as WalletPrivateKeyOptions, j as WalletProviderType, f as WalletReadonlyContext, e as WalletReadonlyOptions, W as WalletRegistry, o as WalletSendTransactionParams, q as WalletSignerContext, p as WalletTransferParams, d as WalletTurnkeyOptions } from './types-BVLpaY4O.js';
9
9
  export { AIAbortError, AIClientConfig, AIError, AIFetchError, AIRequestMetadata, AIResponseError, ChatCompletionChoice, ChatCompletionLogProbs, ChatCompletionResponse, ChatCompletionUsage, ChatMessage, ChatMessageContentPart, ChatMessageContentPartImageUrl, ChatMessageContentPartText, ChatMessageRole, DEFAULT_BASE_URL, DEFAULT_MODEL, DEFAULT_TIMEOUT_MS, FunctionToolDefinition, GenerateTextOptions, GenerateTextResult, GenerationParameters, JsonSchema, ResolvedAIClientConfig, ResponseErrorDetails, StreamTextOptions, StreamTextResult, StreamingEventHandlers, ToolChoice, ToolDefinition, ToolExecutionPolicy, WEBSEARCH_TOOL_DEFINITION, WEBSEARCH_TOOL_NAME, WebSearchOptions, createAIClient, ensureTextContent, flattenMessageContent, generateText, getModelConfig, isStreamingSupported, isToolCallingSupported, listModels, normalizeModelName, resolveConfig, resolveToolset, streamText } from './ai/index.js';
10
- export { AgentDigestRequest, MyToolsResponse, StoreAction, StoreError, StoreEventInput, StoreOptions, StoreResponse, StoreRetrieveParams, StoreRetrieveResult, ToolExecuteRequest, ToolExecuteResponse, executeTool, getMyPerformance, getMyTools, postAgentDigest, retrieve, store } from './store/index.js';
10
+ export { AgentDigestRequest, MyToolsResponse, StoreAction, StoreError, StoreEventInput, StoreEventLevel, StoreOptions, StoreResponse, StoreRetrieveParams, StoreRetrieveResult, ToolExecuteRequest, ToolExecuteResponse, executeTool, getMyPerformance, getMyTools, postAgentDigest, retrieve, store } from './store/index.js';
11
11
  import { ZodSchema } from 'zod';
12
12
  import 'viem';
13
13
  import 'viem/accounts';
package/dist/index.js CHANGED
@@ -1626,6 +1626,29 @@ var walletToolkit = {
1626
1626
  };
1627
1627
 
1628
1628
  // src/store/index.ts
1629
+ var STORE_EVENT_LEVELS = [
1630
+ "decision",
1631
+ "execution",
1632
+ "lifecycle"
1633
+ ];
1634
+ var STORE_EVENT_LEVEL_SET = new Set(STORE_EVENT_LEVELS);
1635
+ var MARKET_REQUIRED_ACTIONS = [
1636
+ "swap",
1637
+ "bridge",
1638
+ "order",
1639
+ "trade",
1640
+ "lend",
1641
+ "borrow",
1642
+ "repay",
1643
+ "stake",
1644
+ "unstake",
1645
+ "withdraw",
1646
+ "provide_liquidity",
1647
+ "remove_liquidity",
1648
+ "claim"
1649
+ ];
1650
+ var MARKET_REQUIRED_ACTIONS_SET = new Set(MARKET_REQUIRED_ACTIONS);
1651
+ var EXECUTION_ACTIONS_SET = new Set(MARKET_REQUIRED_ACTIONS);
1629
1652
  var StoreError = class extends Error {
1630
1653
  constructor(message, status, causeData) {
1631
1654
  super(message);
@@ -1634,13 +1657,57 @@ var StoreError = class extends Error {
1634
1657
  this.name = "StoreError";
1635
1658
  }
1636
1659
  };
1660
+ var normalizeAction = (action) => {
1661
+ const normalized = action?.trim().toLowerCase();
1662
+ return normalized ? normalized : null;
1663
+ };
1664
+ var coerceEventLevel = (value) => {
1665
+ if (typeof value !== "string") return null;
1666
+ const normalized = value.trim().toLowerCase();
1667
+ if (!normalized || !STORE_EVENT_LEVEL_SET.has(normalized)) return null;
1668
+ return normalized;
1669
+ };
1637
1670
  var requiresMarketIdentity = (input) => {
1638
- const action = (input.action ?? "").toLowerCase();
1639
- if (action === "order" || action === "swap" || action === "trade") return true;
1640
- return false;
1671
+ const action = normalizeAction(input.action);
1672
+ if (!action) return false;
1673
+ return MARKET_REQUIRED_ACTIONS_SET.has(action);
1641
1674
  };
1642
1675
  var hasMarketIdentity = (value) => {
1643
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1676
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1677
+ const record = value;
1678
+ const requiredKeys = ["market_type", "venue", "environment", "canonical_symbol"];
1679
+ return requiredKeys.every((key) => {
1680
+ const field = record[key];
1681
+ return typeof field === "string" && field.trim().length > 0;
1682
+ });
1683
+ };
1684
+ var resolveEventLevel = (input) => {
1685
+ const direct = coerceEventLevel(input.eventLevel);
1686
+ if (direct) return direct;
1687
+ const metadataLevel = coerceEventLevel(input.metadata?.eventLevel);
1688
+ if (metadataLevel) return metadataLevel;
1689
+ const action = normalizeAction(input.action);
1690
+ if (action && EXECUTION_ACTIONS_SET.has(action) && (input.metadata?.lifecycle === true || typeof input.metadata?.executionRef === "string" || typeof input.metadata?.parentExecutionRef === "string")) {
1691
+ return "lifecycle";
1692
+ }
1693
+ if (action && EXECUTION_ACTIONS_SET.has(action) || hasMarketIdentity(input.market)) {
1694
+ return "execution";
1695
+ }
1696
+ if (action) return "decision";
1697
+ return null;
1698
+ };
1699
+ var normalizeStoreInput = (input) => {
1700
+ const metadata = { ...input.metadata ?? {} };
1701
+ const eventLevel = resolveEventLevel({ ...input, metadata });
1702
+ if (eventLevel) {
1703
+ metadata.eventLevel = eventLevel;
1704
+ }
1705
+ const hasMetadata = Object.keys(metadata).length > 0;
1706
+ return {
1707
+ ...input,
1708
+ ...eventLevel ? { eventLevel } : {},
1709
+ ...hasMetadata ? { metadata } : {}
1710
+ };
1644
1711
  };
1645
1712
  function resolveConfig(options) {
1646
1713
  const baseUrl = options?.baseUrl ?? process.env.BASE_URL ?? "https://api.openpond.ai";
@@ -1693,8 +1760,26 @@ async function requestJson(url, options, init) {
1693
1760
  }
1694
1761
  }
1695
1762
  async function store(input, options) {
1696
- if (requiresMarketIdentity(input) && !hasMarketIdentity(input.market)) {
1697
- throw new StoreError("market is required for trade events");
1763
+ const normalizedInput = normalizeStoreInput(input);
1764
+ const eventLevel = normalizedInput.eventLevel;
1765
+ const normalizedAction = normalizeAction(normalizedInput.action);
1766
+ if (eventLevel === "execution" || eventLevel === "lifecycle") {
1767
+ if (!normalizedAction || !EXECUTION_ACTIONS_SET.has(normalizedAction)) {
1768
+ throw new StoreError(
1769
+ `eventLevel "${eventLevel}" requires an execution action`
1770
+ );
1771
+ }
1772
+ }
1773
+ if (eventLevel === "execution" && !hasMarketIdentity(normalizedInput.market)) {
1774
+ throw new StoreError(
1775
+ `market is required for execution events. market must include market_type, venue, environment, canonical_symbol`
1776
+ );
1777
+ }
1778
+ const shouldApplyLegacyMarketRule = eventLevel == null || eventLevel === "execution";
1779
+ if (shouldApplyLegacyMarketRule && requiresMarketIdentity(normalizedInput) && !hasMarketIdentity(normalizedInput.market)) {
1780
+ throw new StoreError(
1781
+ `market is required for action "${normalizedInput.action}". market must include market_type, venue, environment, canonical_symbol`
1782
+ );
1698
1783
  }
1699
1784
  const { baseUrl, apiKey, fetchFn } = resolveConfig(options);
1700
1785
  const url = `${baseUrl}/apps/positions/tx`;
@@ -1706,7 +1791,7 @@ async function store(input, options) {
1706
1791
  "content-type": "application/json",
1707
1792
  "openpond-api-key": apiKey
1708
1793
  },
1709
- body: JSON.stringify(input)
1794
+ body: JSON.stringify(normalizedInput)
1710
1795
  });
1711
1796
  } catch (error) {
1712
1797
  throw new StoreError("Failed to reach store endpoint", void 0, error);
@@ -1843,6 +1928,7 @@ var BUILDER_CODE = {
1843
1928
  fee: 100
1844
1929
  };
1845
1930
  var metaCache = /* @__PURE__ */ new Map();
1931
+ var spotMetaCache = /* @__PURE__ */ new Map();
1846
1932
  var perpDexsCache = /* @__PURE__ */ new Map();
1847
1933
  var UNKNOWN_SYMBOL = "UNKNOWN";
1848
1934
  var extractDexPrefix = (value) => {
@@ -1865,6 +1951,14 @@ var normalizeHyperliquidBase = (value) => {
1865
1951
  if (!normalized || normalized === UNKNOWN_SYMBOL) return null;
1866
1952
  return normalized;
1867
1953
  };
1954
+ var normalizeSpotTokenName = (value) => {
1955
+ const raw = (value ?? "").trim().toUpperCase();
1956
+ if (!raw) return "";
1957
+ if (raw.endsWith("0") && raw.length > 1) {
1958
+ return raw.slice(0, -1);
1959
+ }
1960
+ return raw;
1961
+ };
1868
1962
  var parseHyperliquidPair = (value) => {
1869
1963
  if (!value) return null;
1870
1964
  const trimmed = value.trim();
@@ -2011,6 +2105,29 @@ async function getUniverse(args) {
2011
2105
  metaCache.set(cacheKey, { fetchedAt: Date.now(), universe: json.universe });
2012
2106
  return json.universe;
2013
2107
  }
2108
+ async function getSpotMeta(args) {
2109
+ const cacheKey = `${args.environment}:${args.baseUrl}`;
2110
+ const cached = spotMetaCache.get(cacheKey);
2111
+ if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
2112
+ return { universe: cached.universe, tokens: cached.tokens };
2113
+ }
2114
+ const response = await args.fetcher(`${args.baseUrl}/info`, {
2115
+ method: "POST",
2116
+ headers: { "content-type": "application/json" },
2117
+ body: JSON.stringify({ type: "spotMeta" })
2118
+ });
2119
+ const json = await response.json().catch(() => null);
2120
+ if (!response.ok || !json?.universe) {
2121
+ throw new HyperliquidApiError(
2122
+ "Unable to load Hyperliquid spot metadata.",
2123
+ json ?? { status: response.status }
2124
+ );
2125
+ }
2126
+ const universe = json.universe ?? [];
2127
+ const tokens2 = json.tokens ?? [];
2128
+ spotMetaCache.set(cacheKey, { fetchedAt: Date.now(), universe, tokens: tokens2 });
2129
+ return { universe, tokens: tokens2 };
2130
+ }
2014
2131
  function resolveAssetIndex(symbol, universe) {
2015
2132
  const [raw] = symbol.split("-");
2016
2133
  const target = raw.trim();
@@ -2054,11 +2171,57 @@ async function resolveDexIndex(args) {
2054
2171
  }
2055
2172
  return index;
2056
2173
  }
2174
+ function buildSpotTokenIndexMap(tokens2) {
2175
+ const map = /* @__PURE__ */ new Map();
2176
+ for (const token2 of tokens2) {
2177
+ const name = normalizeSpotTokenName(token2?.name);
2178
+ const index = typeof token2?.index === "number" && Number.isFinite(token2.index) ? token2.index : null;
2179
+ if (!name || index == null) continue;
2180
+ if (!map.has(name) || token2?.isCanonical) {
2181
+ map.set(name, index);
2182
+ }
2183
+ }
2184
+ return map;
2185
+ }
2186
+ function resolveSpotTokenIndex(tokenMap, value) {
2187
+ const normalized = normalizeSpotTokenName(value);
2188
+ if (!normalized) return null;
2189
+ const direct = tokenMap.get(normalized);
2190
+ if (direct != null) return direct;
2191
+ if (!normalized.startsWith("U")) {
2192
+ const prefixed = tokenMap.get(`U${normalized}`);
2193
+ if (prefixed != null) return prefixed;
2194
+ }
2195
+ return null;
2196
+ }
2197
+ function resolveSpotMarketIndex(args) {
2198
+ for (let i = 0; i < args.universe.length; i += 1) {
2199
+ const entry = args.universe[i];
2200
+ const tokens2 = Array.isArray(entry?.tokens) ? entry.tokens : null;
2201
+ const baseToken = tokens2?.[0] ?? entry?.baseToken ?? null;
2202
+ const quoteToken = tokens2?.[1] ?? entry?.quoteToken ?? null;
2203
+ if (baseToken === args.baseToken && quoteToken === args.quoteToken) {
2204
+ if (typeof entry?.index === "number" && Number.isFinite(entry.index)) {
2205
+ return entry.index;
2206
+ }
2207
+ return i;
2208
+ }
2209
+ }
2210
+ return null;
2211
+ }
2057
2212
  async function resolveHyperliquidAssetIndex(args) {
2058
2213
  const trimmed = args.symbol.trim();
2059
2214
  if (!trimmed) {
2060
2215
  throw new Error("Hyperliquid symbol must be a non-empty string.");
2061
2216
  }
2217
+ if (trimmed.startsWith("@")) {
2218
+ const rawIndex = trimmed.slice(1).trim();
2219
+ const index = Number(rawIndex);
2220
+ if (!Number.isFinite(index)) {
2221
+ throw new Error(`Hyperliquid spot market index is invalid: ${trimmed}`);
2222
+ }
2223
+ return 1e4 + index;
2224
+ }
2062
2225
  const separator = trimmed.indexOf(":");
2063
2226
  if (separator > 0) {
2064
2227
  const dex = trimmed.slice(0, separator).trim();
@@ -2085,6 +2248,29 @@ async function resolveHyperliquidAssetIndex(args) {
2085
2248
  }
2086
2249
  return 1e5 + dexIndex * 1e4 + assetIndex;
2087
2250
  }
2251
+ const pair = parseHyperliquidPair(trimmed);
2252
+ if (pair) {
2253
+ const { universe: universe2, tokens: tokens2 } = await getSpotMeta({
2254
+ baseUrl: args.baseUrl,
2255
+ environment: args.environment,
2256
+ fetcher: args.fetcher
2257
+ });
2258
+ const tokenMap = buildSpotTokenIndexMap(tokens2);
2259
+ const baseToken = resolveSpotTokenIndex(tokenMap, pair.base);
2260
+ const quoteToken = resolveSpotTokenIndex(tokenMap, pair.quote);
2261
+ if (baseToken == null || quoteToken == null) {
2262
+ throw new Error(`Unknown Hyperliquid spot symbol: ${trimmed}`);
2263
+ }
2264
+ const marketIndex = resolveSpotMarketIndex({
2265
+ universe: universe2,
2266
+ baseToken,
2267
+ quoteToken
2268
+ });
2269
+ if (marketIndex == null) {
2270
+ throw new Error(`Unknown Hyperliquid spot symbol: ${trimmed}`);
2271
+ }
2272
+ return 1e4 + marketIndex;
2273
+ }
2088
2274
  const universe = await getUniverse({
2089
2275
  baseUrl: args.baseUrl,
2090
2276
  environment: args.environment,