@t2000/engine 0.29.0 → 0.30.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.d.ts CHANGED
@@ -1054,6 +1054,10 @@ interface PortfolioInsight {
1054
1054
  type: 'info' | 'warning' | 'suggestion';
1055
1055
  message: string;
1056
1056
  }
1057
+ interface WeekChange {
1058
+ absoluteUsd: number;
1059
+ percentChange: number;
1060
+ }
1057
1061
  interface PortfolioResult {
1058
1062
  totalValue: number;
1059
1063
  walletValue: number;
@@ -1063,6 +1067,9 @@ interface PortfolioResult {
1063
1067
  allocations: AssetAllocation[];
1064
1068
  stablePercentage: number;
1065
1069
  insights: PortfolioInsight[];
1070
+ savingsApy?: number;
1071
+ dailyEarning?: number;
1072
+ weekChange?: WeekChange;
1066
1073
  }
1067
1074
  declare const portfolioAnalysisTool: Tool<{
1068
1075
  address?: string | undefined;
@@ -1102,6 +1109,35 @@ declare const spendingAnalyticsTool: Tool<{
1102
1109
  period?: "all" | "week" | "month" | "year" | undefined;
1103
1110
  }, SpendingResponse>;
1104
1111
 
1112
+ interface YieldSummary {
1113
+ today: number;
1114
+ thisWeek: number;
1115
+ thisMonth: number;
1116
+ allTime: number;
1117
+ currentApy: number;
1118
+ deposited: number;
1119
+ projectedYear: number;
1120
+ sparkline: number[];
1121
+ }
1122
+ declare const yieldSummaryTool: Tool<{}, YieldSummary>;
1123
+
1124
+ interface ActionBreakdown {
1125
+ action: string;
1126
+ count: number;
1127
+ totalAmountUsd: number;
1128
+ }
1129
+ interface ActivitySummary {
1130
+ period: string;
1131
+ totalTransactions: number;
1132
+ byAction: ActionBreakdown[];
1133
+ totalMovedUsd: number;
1134
+ netSavingsUsd: number;
1135
+ yieldEarnedUsd: number;
1136
+ }
1137
+ declare const activitySummaryTool: Tool<{
1138
+ period?: "all" | "week" | "month" | "year" | undefined;
1139
+ }, ActivitySummary>;
1140
+
1105
1141
  declare const defillamaYieldPoolsTool: Tool<{
1106
1142
  limit?: number | undefined;
1107
1143
  chain?: string | undefined;
@@ -1217,4 +1253,4 @@ declare function clearPriceCache(): void;
1217
1253
 
1218
1254
  declare const DEFAULT_SYSTEM_PROMPT = "You are a financial agent on Sui. You manage money and access paid APIs via MPP micropayments.\n\n## Response rules\n- 1-2 sentences max. No bullet lists unless asked. No preambles.\n- Never say \"Would you like me to...\", \"Sure!\", \"Great question!\", \"Absolutely!\" \u2014 just do it or say you can't.\n- Lead with the result. After tool calls, state the outcome with real numbers. Done.\n- Present amounts as $1,234.56 and rates as X.XX% APY.\n- Show top 3 results unless asked for more. Summarize totals in one line.\n\n## Execution rule\nOnly offer to execute actions you have tools for. If you retrieved a quote, data, or information but have no tool to act on it, give the user the result and tell them where to execute manually \u2014 in one sentence. Never say \"Would you like me to proceed?\" unless you have a tool that can actually proceed.\n\n## Before acting\n- ALWAYS call a read tool first before any write tool \u2014 balance_check before save/send/borrow, savings_info before withdraw.\n- Show real numbers from tools \u2014 never fabricate rates, amounts, or balances.\n- When user says \"all\" or an imprecise amount, call the read tool first to get the exact number.\n\n## Tool usage\n- Use tools proactively \u2014 don't refuse requests you can handle.\n- For real-world questions (weather, search, news, prices), use pay_api. Tell the user the cost first.\n- For broad market data (yields across protocols, token prices, TVL, protocol comparisons), use defillama_* tools.\n- To discover Sui protocols, use defillama_sui_protocols first, then defillama_protocol_info with the slug.\n- Run multiple read-only tools in parallel when you need several data points.\n- If a tool errors, say what went wrong and what to try instead. One sentence.\n\n## Savings = USDC only (critical)\n- save_deposit accepts ONLY USDC. No other token can be deposited into savings.\n- When asked \"how much can I save?\", report only the user's USDC wallet balance (saveableUsdc field from balance_check). Other tokens like GOLD, SUI, USDT are NOT saveable and NOT savings positions \u2014 they are just wallet holdings.\n- NEVER say a non-USDC token is \"in savings\" or \"earning APY in savings\" unless it appears in the savings_info positions list. Wallet holdings \u2260 savings.\n- If user wants to save non-USDC tokens, tell them to swap to USDC first. Do NOT auto-chain swap + deposit.\n\n## Multi-step flows\n- \"How much X for Y?\": swap_quote first, then swap_execute if user confirms.\n- \"Swap then save\": swap_execute \u2192 balance_check \u2192 save_deposit. Confirm each step.\n- \"Buy $X of token\": defillama_token_prices \u2192 calculate amount \u2192 swap_execute.\n- \"Best yield on SUI\": compare rates_info (NAVI lending) + defillama_yield_pools (broader) + volo_stats.\n- withdraw supports legacy positions: USDC, USDe, USDsui, SUI. Pass asset param to withdraw a specific token.\n- \"Deposit SUI to earn yield\": volo_stake for SUI liquid staking. save_deposit is USDC only.\n- \"What protocols are on Sui?\": defillama_sui_protocols \u2192 defillama_protocol_info for details.\n\n## Safety\n- Never encourage risky financial behavior.\n- Warn when health factor < 1.5.\n- All amounts in USDC unless stated otherwise.";
1219
1255
 
1220
- export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_SYSTEM_PROMPT, type EngineConfig, type EngineEvent, type HealthFactorResult, type LLMProvider, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type PendingAction, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionResponse, type PositionEntry, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StopReason, type SuiCoinBalance, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolJsonSchema, type ToolResult, TxMutex, WRITE_TOOLS, type WalletCoin, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool };
1256
+ export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_SYSTEM_PROMPT, type EngineConfig, type EngineEvent, type HealthFactorResult, type LLMProvider, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type PendingAction, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionResponse, type PositionEntry, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StopReason, type SuiCoinBalance, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolJsonSchema, type ToolResult, TxMutex, WRITE_TOOLS, type WalletCoin, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
package/dist/index.js CHANGED
@@ -1802,12 +1802,35 @@ var portfolioAnalysisTool = buildTool({
1802
1802
  let savingsValue = 0;
1803
1803
  let debtValue = 0;
1804
1804
  let healthFactor = null;
1805
+ let savingsApy;
1806
+ let dailyEarning;
1805
1807
  if (context.positionFetcher) {
1806
1808
  try {
1807
1809
  const positions = await context.positionFetcher(address);
1808
1810
  savingsValue = positions.savings ?? 0;
1809
1811
  debtValue = positions.borrows ?? 0;
1810
1812
  healthFactor = positions.healthFactor ?? null;
1813
+ if (typeof positions.savingsRate === "number" && positions.savingsRate > 0) {
1814
+ savingsApy = positions.savingsRate;
1815
+ dailyEarning = savingsValue * savingsApy / 365;
1816
+ }
1817
+ } catch {
1818
+ }
1819
+ }
1820
+ let weekChange;
1821
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
1822
+ if (apiUrl && address) {
1823
+ try {
1824
+ const histRes = await fetch(
1825
+ `${apiUrl}/api/analytics/portfolio-history?days=7`,
1826
+ { headers: { "x-sui-address": address }, signal: context.signal }
1827
+ );
1828
+ if (histRes.ok) {
1829
+ const hist = await histRes.json();
1830
+ if (hist.change && hist.change.absoluteUsd !== 0) {
1831
+ weekChange = hist.change;
1832
+ }
1833
+ }
1811
1834
  } catch {
1812
1835
  }
1813
1836
  }
@@ -1857,7 +1880,10 @@ var portfolioAnalysisTool = buildTool({
1857
1880
  healthFactor,
1858
1881
  allocations: allocations.slice(0, 10),
1859
1882
  stablePercentage,
1860
- insights
1883
+ insights,
1884
+ savingsApy,
1885
+ dailyEarning,
1886
+ weekChange
1861
1887
  };
1862
1888
  const topLine = `Total: $${totalValue.toFixed(2)} | Wallet: $${walletValue.toFixed(2)} | Savings: $${savingsValue.toFixed(2)}`;
1863
1889
  const insightLines = insights.map((i) => `${i.type === "warning" ? "\u26A0" : "\u2192"} ${i.message}`).join("\n");
@@ -2704,6 +2730,97 @@ var spendingAnalyticsTool = buildTool({
2704
2730
  }
2705
2731
  }
2706
2732
  });
2733
+ var yieldSummaryTool = buildTool({
2734
+ name: "yield_summary",
2735
+ description: "Returns yield earnings breakdown: today, this week, this month, all-time, current APY, deposited amount, projected yearly earnings, and a monthly sparkline. Use when the user asks about yield, earnings, or how much they have earned.",
2736
+ inputSchema: z.object({}),
2737
+ jsonSchema: { type: "object", properties: {}, required: [] },
2738
+ isReadOnly: true,
2739
+ async call(_input, context) {
2740
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2741
+ const address = context.walletAddress;
2742
+ const empty = {
2743
+ today: 0,
2744
+ thisWeek: 0,
2745
+ thisMonth: 0,
2746
+ allTime: 0,
2747
+ currentApy: 0,
2748
+ deposited: 0,
2749
+ projectedYear: 0,
2750
+ sparkline: []
2751
+ };
2752
+ if (!apiUrl || !address) {
2753
+ return { data: empty, displayText: "Yield summary not available." };
2754
+ }
2755
+ try {
2756
+ const res = await fetch(
2757
+ `${apiUrl}/api/analytics/yield-summary?address=${address}`,
2758
+ { headers: { "x-sui-address": address }, signal: context.signal }
2759
+ );
2760
+ if (!res.ok) {
2761
+ return { data: empty, displayText: `Could not fetch yield data (HTTP ${res.status}).` };
2762
+ }
2763
+ const data = await res.json();
2764
+ const apy = data.currentApy ?? 0;
2765
+ const apyPct = apy < 1 ? (apy * 100).toFixed(2) : apy.toFixed(2);
2766
+ return {
2767
+ data,
2768
+ displayText: data.allTime > 0 ? `You've earned $${data.allTime.toFixed(2)} all-time ($${data.today.toFixed(4)} today). Current APY: ${apyPct}%. Deposited: $${data.deposited.toFixed(2)}. Projected: $${data.projectedYear.toFixed(2)}/year.` : `No yield earnings yet. Deposit USDC to start earning ${apyPct}% APY.`
2769
+ };
2770
+ } catch {
2771
+ return { data: empty, displayText: "Error fetching yield summary." };
2772
+ }
2773
+ }
2774
+ });
2775
+ var activitySummaryTool = buildTool({
2776
+ name: "activity_summary",
2777
+ description: "Returns a categorised DeFi activity summary for a period: transaction count, breakdown by action type (saves, sends, borrows, repayments, swaps, payments), total moved, net savings change, and yield earned. Use when the user asks about their activity, transaction history summary, or what they have done recently.",
2778
+ inputSchema: z.object({
2779
+ period: z.enum(["week", "month", "year", "all"]).optional().describe("Time period. Defaults to current month.")
2780
+ }),
2781
+ jsonSchema: {
2782
+ type: "object",
2783
+ properties: {
2784
+ period: { type: "string", enum: ["week", "month", "year", "all"] }
2785
+ }
2786
+ },
2787
+ isReadOnly: true,
2788
+ async call(input, context) {
2789
+ const period = input.period ?? "month";
2790
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2791
+ const address = context.walletAddress;
2792
+ const empty = {
2793
+ period,
2794
+ totalTransactions: 0,
2795
+ byAction: [],
2796
+ totalMovedUsd: 0,
2797
+ netSavingsUsd: 0,
2798
+ yieldEarnedUsd: 0
2799
+ };
2800
+ if (!apiUrl || !address) {
2801
+ return { data: empty, displayText: "Activity summary not available." };
2802
+ }
2803
+ try {
2804
+ const res = await fetch(
2805
+ `${apiUrl}/api/analytics/activity-summary?address=${address}&period=${period}`,
2806
+ { headers: { "x-sui-address": address }, signal: context.signal }
2807
+ );
2808
+ if (!res.ok) {
2809
+ return { data: empty, displayText: `Could not fetch activity data (HTTP ${res.status}).` };
2810
+ }
2811
+ const data = await res.json();
2812
+ const sorted = [...data.byAction ?? []].sort((a, b) => b.count - a.count);
2813
+ const top = sorted.slice(0, 3).map((a) => `${a.action} (${a.count})`).join(", ");
2814
+ const periodLabel = data.period === "all" ? "all time" : `this ${data.period}`;
2815
+ return {
2816
+ data,
2817
+ displayText: data.totalTransactions > 0 ? `${data.totalTransactions} transactions ${periodLabel}. Top: ${top}. Total moved: $${data.totalMovedUsd.toFixed(2)}. Net savings: $${data.netSavingsUsd.toFixed(2)}.` : `No activity recorded for ${periodLabel}.`
2818
+ };
2819
+ } catch {
2820
+ return { data: empty, displayText: "Error fetching activity summary." };
2821
+ }
2822
+ }
2823
+ });
2707
2824
  var LLAMA_API2 = "https://api.llama.fi";
2708
2825
  var YIELDS_API2 = "https://yields.llama.fi";
2709
2826
  var COINS_API = "https://coins.llama.fi";
@@ -3018,7 +3135,9 @@ var READ_TOOLS = [
3018
3135
  cancelInvoiceTool,
3019
3136
  createPaymentLinkTool,
3020
3137
  createInvoiceTool,
3021
- spendingAnalyticsTool
3138
+ spendingAnalyticsTool,
3139
+ yieldSummaryTool,
3140
+ activitySummaryTool
3022
3141
  ];
3023
3142
  var WRITE_TOOLS = [
3024
3143
  saveDepositTool,
@@ -4325,6 +4444,6 @@ function sanitizeAnthropicMessages(messages) {
4325
4444
  return merged;
4326
4445
  }
4327
4446
 
4328
- export { AnthropicProvider, CANVAS_TEMPLATES, CostTracker, DEFAULT_SYSTEM_PROMPT, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, NaviTools, QueryEngine, READ_TOOLS, TxMutex, WRITE_TOOLS, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool };
4447
+ export { AnthropicProvider, CANVAS_TEMPLATES, CostTracker, DEFAULT_SYSTEM_PROMPT, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, NaviTools, QueryEngine, READ_TOOLS, TxMutex, WRITE_TOOLS, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
4329
4448
  //# sourceMappingURL=index.js.map
4330
4449
  //# sourceMappingURL=index.js.map