@t2000/engine 0.28.9 → 0.29.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
@@ -1091,6 +1091,17 @@ declare const protocolDeepDiveTool: Tool<{
1091
1091
  protocol: string;
1092
1092
  }, ProtocolProfile>;
1093
1093
 
1094
+ interface SpendingResponse {
1095
+ period: string;
1096
+ totalSpent: number;
1097
+ requestCount: number;
1098
+ serviceCount: number;
1099
+ byService: unknown[];
1100
+ }
1101
+ declare const spendingAnalyticsTool: Tool<{
1102
+ period?: "all" | "week" | "month" | "year" | undefined;
1103
+ }, SpendingResponse>;
1104
+
1094
1105
  declare const defillamaYieldPoolsTool: Tool<{
1095
1106
  limit?: number | undefined;
1096
1107
  chain?: string | undefined;
@@ -1206,4 +1217,4 @@ declare function clearPriceCache(): void;
1206
1217
 
1207
1218
  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
1219
 
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 };
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 };
package/dist/index.js CHANGED
@@ -2450,6 +2450,12 @@ var CANVAS_TEMPLATES = [
2450
2450
  "watch_address",
2451
2451
  "full_portfolio"
2452
2452
  ];
2453
+ function normalizeSavingsRate(raw, fallback = 4.5) {
2454
+ const r = raw ?? 0;
2455
+ if (r > 0 && r < 1) return r * 100;
2456
+ if (r > 0) return r;
2457
+ return fallback;
2458
+ }
2453
2459
  var CANVAS_TITLES = {
2454
2460
  activity_heatmap: "On-Chain Activity",
2455
2461
  portfolio_timeline: "Net Worth Over Time",
@@ -2460,26 +2466,20 @@ var CANVAS_TITLES = {
2460
2466
  watch_address: "Watch Address",
2461
2467
  full_portfolio: "Full Portfolio Overview"
2462
2468
  };
2463
- var PHASE_3_TEMPLATES = /* @__PURE__ */ new Set([
2464
- "activity_heatmap",
2465
- "portfolio_timeline",
2466
- "spending_breakdown",
2467
- "full_portfolio"
2468
- ]);
2469
2469
  var renderCanvasTool = buildTool({
2470
2470
  name: "render_canvas",
2471
2471
  description: `Renders an interactive financial canvas inline in the chat.
2472
2472
 
2473
2473
  Use when the user asks for a visual chart, simulator, or financial overview. Pick the most relevant template:
2474
2474
 
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)
2475
+ - activity_heatmap \u2014 on-chain transaction history as a GitHub-style heatmap (WORKS NOW \u2014 loads from wallet)
2476
+ - portfolio_timeline \u2014 net worth over time, wallet/savings/debt breakdown (WORKS NOW \u2014 daily snapshots)
2477
2477
  - yield_projector \u2014 compound yield simulator with amount/APY/period sliders (WORKS NOW \u2014 client-side)
2478
2478
  - health_simulator \u2014 borrow health factor simulator with collateral/debt sliders (WORKS NOW \u2014 uses current position)
2479
2479
  - 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)
2480
+ - spending_breakdown \u2014 spending by service category (WORKS NOW \u2014 from AppEvent + ServicePurchase)
2481
+ - watch_address \u2014 portfolio overview for any public Sui address (WORKS NOW \u2014 pass address in params)
2482
+ - full_portfolio \u2014 4-panel overview: savings, health, activity, spending (WORKS NOW \u2014 aggregates all data)
2483
2483
 
2484
2484
  Always prefer the canvas for visualisation requests. After rendering, offer to explain what the user sees.`,
2485
2485
  inputSchema: z.object({
@@ -2511,31 +2511,95 @@ Always prefer the canvas for visualisation requests. After rendering, offer to e
2511
2511
  async call(input, context) {
2512
2512
  const { template, params } = input;
2513
2513
  const title = CANVAS_TITLES[template];
2514
- if (PHASE_3_TEMPLATES.has(template)) {
2514
+ if (template === "full_portfolio") {
2515
+ const pos = context.serverPositions;
2516
+ const rate = normalizeSavingsRate(pos?.savingsRate);
2517
+ const savings = pos?.savings ?? 0;
2518
+ const borrows = pos?.borrows ?? 0;
2515
2519
  return {
2516
2520
  data: {
2517
2521
  __canvas: true,
2518
2522
  template,
2519
2523
  title,
2520
- templateData: { available: false, message: "This canvas will be available in Phase 3 when analytics APIs are ready." }
2524
+ templateData: {
2525
+ available: true,
2526
+ address: context.walletAddress ?? "",
2527
+ currentSavings: savings,
2528
+ currentDebt: borrows,
2529
+ healthFactor: pos?.healthFactor ?? null,
2530
+ savingsRate: rate
2531
+ }
2521
2532
  },
2522
- displayText: `Canvas template "${title}" is coming soon.`
2533
+ displayText: `Opened Full Portfolio Overview.`
2523
2534
  };
2524
2535
  }
2525
2536
  if (template === "watch_address") {
2537
+ const targetAddress = params?.address ?? "";
2538
+ if (!targetAddress || !targetAddress.startsWith("0x")) {
2539
+ return {
2540
+ data: {
2541
+ __canvas: true,
2542
+ template,
2543
+ title,
2544
+ templateData: { available: false, message: "Please provide a valid Sui address to watch." }
2545
+ },
2546
+ displayText: "No valid address provided. Ask the user for a Sui address."
2547
+ };
2548
+ }
2549
+ return {
2550
+ data: {
2551
+ __canvas: true,
2552
+ template,
2553
+ title: `Watch ${targetAddress.slice(0, 6)}\u2026${targetAddress.slice(-4)}`,
2554
+ templateData: { available: true, address: targetAddress }
2555
+ },
2556
+ displayText: `Opened Watch Address canvas for ${targetAddress.slice(0, 6)}\u2026${targetAddress.slice(-4)}.`
2557
+ };
2558
+ }
2559
+ if (template === "portfolio_timeline") {
2526
2560
  return {
2527
2561
  data: {
2528
2562
  __canvas: true,
2529
2563
  template,
2530
2564
  title,
2531
- templateData: { available: false, address: params?.address ?? null, message: "Watch Address canvas is coming soon." }
2565
+ templateData: {
2566
+ available: true,
2567
+ address: context.walletAddress ?? ""
2568
+ }
2532
2569
  },
2533
- displayText: `Canvas template "${title}" is coming soon.`
2570
+ displayText: `Opened Portfolio Timeline. Shows your net worth, savings, and debt over time.`
2571
+ };
2572
+ }
2573
+ if (template === "spending_breakdown") {
2574
+ return {
2575
+ data: {
2576
+ __canvas: true,
2577
+ template,
2578
+ title,
2579
+ templateData: {
2580
+ available: true,
2581
+ address: context.walletAddress ?? ""
2582
+ }
2583
+ },
2584
+ displayText: `Opened Spending Breakdown. Shows your service spending by category.`
2585
+ };
2586
+ }
2587
+ if (template === "activity_heatmap") {
2588
+ return {
2589
+ data: {
2590
+ __canvas: true,
2591
+ template,
2592
+ title,
2593
+ templateData: {
2594
+ available: true,
2595
+ address: context.walletAddress ?? ""
2596
+ }
2597
+ },
2598
+ displayText: `Opened Activity Heatmap for your wallet. Click any day to explore transactions.`
2534
2599
  };
2535
2600
  }
2536
2601
  const positions = context.serverPositions;
2537
- const rawRate = positions?.savingsRate ?? 0;
2538
- const savingsRate = rawRate > 0 && rawRate < 1 ? rawRate * 100 : rawRate > 0 ? rawRate : 4.5;
2602
+ const savingsRate = normalizeSavingsRate(positions?.savingsRate);
2539
2603
  const healthFactor = positions?.healthFactor ?? null;
2540
2604
  const totalSavings = positions?.savings ?? 0;
2541
2605
  const totalBorrows = positions?.borrows ?? 0;
@@ -2596,6 +2660,50 @@ Always prefer the canvas for visualisation requests. After rendering, offer to e
2596
2660
  };
2597
2661
  }
2598
2662
  });
2663
+ var spendingAnalyticsTool = buildTool({
2664
+ name: "spending_analytics",
2665
+ 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.",
2666
+ inputSchema: z.object({
2667
+ period: z.enum(["week", "month", "year", "all"]).optional().describe("Time period. Defaults to current month.")
2668
+ }),
2669
+ jsonSchema: {
2670
+ type: "object",
2671
+ properties: {
2672
+ period: { type: "string", enum: ["week", "month", "year", "all"] }
2673
+ }
2674
+ },
2675
+ isReadOnly: true,
2676
+ async call(input, context) {
2677
+ const period = input.period ?? "month";
2678
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2679
+ const address = context.walletAddress;
2680
+ const empty = { period, totalSpent: 0, requestCount: 0, serviceCount: 0, byService: [] };
2681
+ if (!apiUrl || !address) {
2682
+ return { data: empty, displayText: "Spending analytics not available." };
2683
+ }
2684
+ try {
2685
+ const res = await fetch(
2686
+ `${apiUrl}/api/analytics/spending?address=${address}&period=${period}`,
2687
+ {
2688
+ headers: { "x-sui-address": address },
2689
+ signal: context.signal
2690
+ }
2691
+ );
2692
+ if (!res.ok) {
2693
+ return { data: empty, displayText: `Could not fetch spending data (HTTP ${res.status}).` };
2694
+ }
2695
+ const data = await res.json();
2696
+ const total = data.totalSpent ?? 0;
2697
+ const count = data.requestCount ?? 0;
2698
+ return {
2699
+ data,
2700
+ 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}.`
2701
+ };
2702
+ } catch {
2703
+ return { data: empty, displayText: "Error fetching spending analytics." };
2704
+ }
2705
+ }
2706
+ });
2599
2707
  var LLAMA_API2 = "https://api.llama.fi";
2600
2708
  var YIELDS_API2 = "https://yields.llama.fi";
2601
2709
  var COINS_API = "https://coins.llama.fi";
@@ -2909,7 +3017,8 @@ var READ_TOOLS = [
2909
3017
  listInvoicesTool,
2910
3018
  cancelInvoiceTool,
2911
3019
  createPaymentLinkTool,
2912
- createInvoiceTool
3020
+ createInvoiceTool,
3021
+ spendingAnalyticsTool
2913
3022
  ];
2914
3023
  var WRITE_TOOLS = [
2915
3024
  saveDepositTool,
@@ -4216,6 +4325,6 @@ function sanitizeAnthropicMessages(messages) {
4216
4325
  return merged;
4217
4326
  }
4218
4327
 
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 };
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 };
4220
4329
  //# sourceMappingURL=index.js.map
4221
4330
  //# sourceMappingURL=index.js.map