@t2000/engine 0.28.9 → 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;
@@ -1091,6 +1098,46 @@ declare const protocolDeepDiveTool: Tool<{
1091
1098
  protocol: string;
1092
1099
  }, ProtocolProfile>;
1093
1100
 
1101
+ interface SpendingResponse {
1102
+ period: string;
1103
+ totalSpent: number;
1104
+ requestCount: number;
1105
+ serviceCount: number;
1106
+ byService: unknown[];
1107
+ }
1108
+ declare const spendingAnalyticsTool: Tool<{
1109
+ period?: "all" | "week" | "month" | "year" | undefined;
1110
+ }, SpendingResponse>;
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
+
1094
1141
  declare const defillamaYieldPoolsTool: Tool<{
1095
1142
  limit?: number | undefined;
1096
1143
  chain?: string | undefined;
@@ -1206,4 +1253,4 @@ declare function clearPriceCache(): void;
1206
1253
 
1207
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.";
1208
1255
 
1209
- 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, 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");
@@ -2450,6 +2476,12 @@ var CANVAS_TEMPLATES = [
2450
2476
  "watch_address",
2451
2477
  "full_portfolio"
2452
2478
  ];
2479
+ function normalizeSavingsRate(raw, fallback = 4.5) {
2480
+ const r = raw ?? 0;
2481
+ if (r > 0 && r < 1) return r * 100;
2482
+ if (r > 0) return r;
2483
+ return fallback;
2484
+ }
2453
2485
  var CANVAS_TITLES = {
2454
2486
  activity_heatmap: "On-Chain Activity",
2455
2487
  portfolio_timeline: "Net Worth Over Time",
@@ -2460,26 +2492,20 @@ var CANVAS_TITLES = {
2460
2492
  watch_address: "Watch Address",
2461
2493
  full_portfolio: "Full Portfolio Overview"
2462
2494
  };
2463
- var PHASE_3_TEMPLATES = /* @__PURE__ */ new Set([
2464
- "activity_heatmap",
2465
- "portfolio_timeline",
2466
- "spending_breakdown",
2467
- "full_portfolio"
2468
- ]);
2469
2495
  var renderCanvasTool = buildTool({
2470
2496
  name: "render_canvas",
2471
2497
  description: `Renders an interactive financial canvas inline in the chat.
2472
2498
 
2473
2499
  Use when the user asks for a visual chart, simulator, or financial overview. Pick the most relevant template:
2474
2500
 
2475
- - activity_heatmap \u2014 on-chain transaction history as a GitHub-style heatmap (coming soon \u2014 needs Phase 3 data)
2476
- - portfolio_timeline \u2014 net worth over time, wallet/savings/debt breakdown (coming soon \u2014 needs Phase 3 data)
2501
+ - activity_heatmap \u2014 on-chain transaction history as a GitHub-style heatmap (WORKS NOW \u2014 loads from wallet)
2502
+ - portfolio_timeline \u2014 net worth over time, wallet/savings/debt breakdown (WORKS NOW \u2014 daily snapshots)
2477
2503
  - yield_projector \u2014 compound yield simulator with amount/APY/period sliders (WORKS NOW \u2014 client-side)
2478
2504
  - health_simulator \u2014 borrow health factor simulator with collateral/debt sliders (WORKS NOW \u2014 uses current position)
2479
2505
  - dca_planner \u2014 savings plan curve for regular monthly deposits (WORKS NOW \u2014 client-side)
2480
- - spending_breakdown \u2014 spending by service category (coming soon \u2014 needs Phase 3 data)
2481
- - watch_address \u2014 portfolio overview for any public Sui address (coming soon \u2014 CA-6)
2482
- - full_portfolio \u2014 4-panel overview: heatmap, timeline, yield, HF (coming soon \u2014 CA-7)
2506
+ - spending_breakdown \u2014 spending by service category (WORKS NOW \u2014 from AppEvent + ServicePurchase)
2507
+ - watch_address \u2014 portfolio overview for any public Sui address (WORKS NOW \u2014 pass address in params)
2508
+ - full_portfolio \u2014 4-panel overview: savings, health, activity, spending (WORKS NOW \u2014 aggregates all data)
2483
2509
 
2484
2510
  Always prefer the canvas for visualisation requests. After rendering, offer to explain what the user sees.`,
2485
2511
  inputSchema: z.object({
@@ -2511,31 +2537,95 @@ Always prefer the canvas for visualisation requests. After rendering, offer to e
2511
2537
  async call(input, context) {
2512
2538
  const { template, params } = input;
2513
2539
  const title = CANVAS_TITLES[template];
2514
- if (PHASE_3_TEMPLATES.has(template)) {
2540
+ if (template === "full_portfolio") {
2541
+ const pos = context.serverPositions;
2542
+ const rate = normalizeSavingsRate(pos?.savingsRate);
2543
+ const savings = pos?.savings ?? 0;
2544
+ const borrows = pos?.borrows ?? 0;
2515
2545
  return {
2516
2546
  data: {
2517
2547
  __canvas: true,
2518
2548
  template,
2519
2549
  title,
2520
- templateData: { available: false, message: "This canvas will be available in Phase 3 when analytics APIs are ready." }
2550
+ templateData: {
2551
+ available: true,
2552
+ address: context.walletAddress ?? "",
2553
+ currentSavings: savings,
2554
+ currentDebt: borrows,
2555
+ healthFactor: pos?.healthFactor ?? null,
2556
+ savingsRate: rate
2557
+ }
2521
2558
  },
2522
- displayText: `Canvas template "${title}" is coming soon.`
2559
+ displayText: `Opened Full Portfolio Overview.`
2523
2560
  };
2524
2561
  }
2525
2562
  if (template === "watch_address") {
2563
+ const targetAddress = params?.address ?? "";
2564
+ if (!targetAddress || !targetAddress.startsWith("0x")) {
2565
+ return {
2566
+ data: {
2567
+ __canvas: true,
2568
+ template,
2569
+ title,
2570
+ templateData: { available: false, message: "Please provide a valid Sui address to watch." }
2571
+ },
2572
+ displayText: "No valid address provided. Ask the user for a Sui address."
2573
+ };
2574
+ }
2575
+ return {
2576
+ data: {
2577
+ __canvas: true,
2578
+ template,
2579
+ title: `Watch ${targetAddress.slice(0, 6)}\u2026${targetAddress.slice(-4)}`,
2580
+ templateData: { available: true, address: targetAddress }
2581
+ },
2582
+ displayText: `Opened Watch Address canvas for ${targetAddress.slice(0, 6)}\u2026${targetAddress.slice(-4)}.`
2583
+ };
2584
+ }
2585
+ if (template === "portfolio_timeline") {
2526
2586
  return {
2527
2587
  data: {
2528
2588
  __canvas: true,
2529
2589
  template,
2530
2590
  title,
2531
- templateData: { available: false, address: params?.address ?? null, message: "Watch Address canvas is coming soon." }
2591
+ templateData: {
2592
+ available: true,
2593
+ address: context.walletAddress ?? ""
2594
+ }
2595
+ },
2596
+ displayText: `Opened Portfolio Timeline. Shows your net worth, savings, and debt over time.`
2597
+ };
2598
+ }
2599
+ if (template === "spending_breakdown") {
2600
+ return {
2601
+ data: {
2602
+ __canvas: true,
2603
+ template,
2604
+ title,
2605
+ templateData: {
2606
+ available: true,
2607
+ address: context.walletAddress ?? ""
2608
+ }
2609
+ },
2610
+ displayText: `Opened Spending Breakdown. Shows your service spending by category.`
2611
+ };
2612
+ }
2613
+ if (template === "activity_heatmap") {
2614
+ return {
2615
+ data: {
2616
+ __canvas: true,
2617
+ template,
2618
+ title,
2619
+ templateData: {
2620
+ available: true,
2621
+ address: context.walletAddress ?? ""
2622
+ }
2532
2623
  },
2533
- displayText: `Canvas template "${title}" is coming soon.`
2624
+ displayText: `Opened Activity Heatmap for your wallet. Click any day to explore transactions.`
2534
2625
  };
2535
2626
  }
2536
2627
  const positions = context.serverPositions;
2537
- const rawRate = positions?.savingsRate ?? 0;
2538
- const savingsRate = rawRate > 0 && rawRate < 1 ? rawRate * 100 : rawRate > 0 ? rawRate : 4.5;
2628
+ const savingsRate = normalizeSavingsRate(positions?.savingsRate);
2539
2629
  const healthFactor = positions?.healthFactor ?? null;
2540
2630
  const totalSavings = positions?.savings ?? 0;
2541
2631
  const totalBorrows = positions?.borrows ?? 0;
@@ -2596,6 +2686,141 @@ Always prefer the canvas for visualisation requests. After rendering, offer to e
2596
2686
  };
2597
2687
  }
2598
2688
  });
2689
+ var spendingAnalyticsTool = buildTool({
2690
+ name: "spending_analytics",
2691
+ description: "Returns MPP service spending breakdown for a period. Shows total spent, request count, and breakdown by service/category. Use when the user asks about their API spending, service usage, or costs.",
2692
+ inputSchema: z.object({
2693
+ period: z.enum(["week", "month", "year", "all"]).optional().describe("Time period. Defaults to current month.")
2694
+ }),
2695
+ jsonSchema: {
2696
+ type: "object",
2697
+ properties: {
2698
+ period: { type: "string", enum: ["week", "month", "year", "all"] }
2699
+ }
2700
+ },
2701
+ isReadOnly: true,
2702
+ async call(input, context) {
2703
+ const period = input.period ?? "month";
2704
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2705
+ const address = context.walletAddress;
2706
+ const empty = { period, totalSpent: 0, requestCount: 0, serviceCount: 0, byService: [] };
2707
+ if (!apiUrl || !address) {
2708
+ return { data: empty, displayText: "Spending analytics not available." };
2709
+ }
2710
+ try {
2711
+ const res = await fetch(
2712
+ `${apiUrl}/api/analytics/spending?address=${address}&period=${period}`,
2713
+ {
2714
+ headers: { "x-sui-address": address },
2715
+ signal: context.signal
2716
+ }
2717
+ );
2718
+ if (!res.ok) {
2719
+ return { data: empty, displayText: `Could not fetch spending data (HTTP ${res.status}).` };
2720
+ }
2721
+ const data = await res.json();
2722
+ const total = data.totalSpent ?? 0;
2723
+ const count = data.requestCount ?? 0;
2724
+ return {
2725
+ data,
2726
+ displayText: total > 0 ? `You spent $${total.toFixed(2)} across ${count} request${count !== 1 ? "s" : ""} on ${data.serviceCount} service${data.serviceCount !== 1 ? "s" : ""} (${data.period}).` : `No service spending recorded for ${data.period}.`
2727
+ };
2728
+ } catch {
2729
+ return { data: empty, displayText: "Error fetching spending analytics." };
2730
+ }
2731
+ }
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
+ });
2599
2824
  var LLAMA_API2 = "https://api.llama.fi";
2600
2825
  var YIELDS_API2 = "https://yields.llama.fi";
2601
2826
  var COINS_API = "https://coins.llama.fi";
@@ -2909,7 +3134,10 @@ var READ_TOOLS = [
2909
3134
  listInvoicesTool,
2910
3135
  cancelInvoiceTool,
2911
3136
  createPaymentLinkTool,
2912
- createInvoiceTool
3137
+ createInvoiceTool,
3138
+ spendingAnalyticsTool,
3139
+ yieldSummaryTool,
3140
+ activitySummaryTool
2913
3141
  ];
2914
3142
  var WRITE_TOOLS = [
2915
3143
  saveDepositTool,
@@ -4216,6 +4444,6 @@ function sanitizeAnthropicMessages(messages) {
4216
4444
  return merged;
4217
4445
  }
4218
4446
 
4219
- 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, 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 };
4220
4448
  //# sourceMappingURL=index.js.map
4221
4449
  //# sourceMappingURL=index.js.map