@t2000/engine 0.28.7 → 0.28.9

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
@@ -52,6 +52,13 @@ type EngineEvent = {
52
52
  } | {
53
53
  type: 'error';
54
54
  error: Error;
55
+ } | {
56
+ /** Emitted when a tool result carries a canvas payload (__canvas: true). */
57
+ type: 'canvas';
58
+ template: string;
59
+ data: unknown;
60
+ title: string;
61
+ toolUseId: string;
55
62
  };
56
63
  type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'max_turns' | 'error';
57
64
  /**
@@ -365,6 +372,12 @@ type SSEEvent = {
365
372
  } | {
366
373
  type: 'error';
367
374
  message: string;
375
+ } | {
376
+ type: 'canvas';
377
+ template: string;
378
+ data: unknown;
379
+ title: string;
380
+ toolUseId: string;
368
381
  };
369
382
  declare function serializeSSE(event: SSEEvent): string;
370
383
  declare function parseSSE(raw: string): SSEEvent | null;
@@ -784,6 +797,16 @@ declare class AnthropicProvider implements LLMProvider {
784
797
  chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
785
798
  }
786
799
 
800
+ declare const CANVAS_TEMPLATES: readonly ["activity_heatmap", "portfolio_timeline", "yield_projector", "health_simulator", "dca_planner", "spending_breakdown", "watch_address", "full_portfolio"];
801
+ type CanvasTemplate = (typeof CANVAS_TEMPLATES)[number];
802
+ declare const renderCanvasTool: Tool<{
803
+ template: "activity_heatmap" | "portfolio_timeline" | "yield_projector" | "health_simulator" | "dca_planner" | "spending_breakdown" | "watch_address" | "full_portfolio";
804
+ params?: {
805
+ address?: string | undefined;
806
+ period?: "1m" | "3m" | "6m" | "1y" | undefined;
807
+ } | undefined;
808
+ }, unknown>;
809
+
787
810
  declare const balanceCheckTool: Tool<{}, {
788
811
  available: number;
789
812
  savings: number;
@@ -1183,4 +1206,4 @@ declare function clearPriceCache(): void;
1183
1206
 
1184
1207
  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.";
1185
1208
 
1186
- export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, 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, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool };
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 };
package/dist/index.js CHANGED
@@ -2440,6 +2440,162 @@ var listInvoicesTool = buildTool({
2440
2440
  }
2441
2441
  }
2442
2442
  });
2443
+ var CANVAS_TEMPLATES = [
2444
+ "activity_heatmap",
2445
+ "portfolio_timeline",
2446
+ "yield_projector",
2447
+ "health_simulator",
2448
+ "dca_planner",
2449
+ "spending_breakdown",
2450
+ "watch_address",
2451
+ "full_portfolio"
2452
+ ];
2453
+ var CANVAS_TITLES = {
2454
+ activity_heatmap: "On-Chain Activity",
2455
+ portfolio_timeline: "Net Worth Over Time",
2456
+ yield_projector: "Yield Projector",
2457
+ health_simulator: "Health Factor Simulator",
2458
+ dca_planner: "Savings Plan",
2459
+ spending_breakdown: "Spending Breakdown",
2460
+ watch_address: "Watch Address",
2461
+ full_portfolio: "Full Portfolio Overview"
2462
+ };
2463
+ var PHASE_3_TEMPLATES = /* @__PURE__ */ new Set([
2464
+ "activity_heatmap",
2465
+ "portfolio_timeline",
2466
+ "spending_breakdown",
2467
+ "full_portfolio"
2468
+ ]);
2469
+ var renderCanvasTool = buildTool({
2470
+ name: "render_canvas",
2471
+ description: `Renders an interactive financial canvas inline in the chat.
2472
+
2473
+ Use when the user asks for a visual chart, simulator, or financial overview. Pick the most relevant template:
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)
2477
+ - yield_projector \u2014 compound yield simulator with amount/APY/period sliders (WORKS NOW \u2014 client-side)
2478
+ - health_simulator \u2014 borrow health factor simulator with collateral/debt sliders (WORKS NOW \u2014 uses current position)
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)
2483
+
2484
+ Always prefer the canvas for visualisation requests. After rendering, offer to explain what the user sees.`,
2485
+ inputSchema: z.object({
2486
+ template: z.enum(CANVAS_TEMPLATES).describe("Which canvas template to render"),
2487
+ params: z.object({
2488
+ period: z.enum(["1m", "3m", "6m", "1y"]).optional().describe("Time period for time-based templates"),
2489
+ address: z.string().optional().describe("Sui address for watch_address template")
2490
+ }).optional()
2491
+ }),
2492
+ jsonSchema: {
2493
+ type: "object",
2494
+ properties: {
2495
+ template: {
2496
+ type: "string",
2497
+ enum: CANVAS_TEMPLATES,
2498
+ description: "Which canvas template to render"
2499
+ },
2500
+ params: {
2501
+ type: "object",
2502
+ properties: {
2503
+ period: { type: "string", enum: ["1m", "3m", "6m", "1y"] },
2504
+ address: { type: "string" }
2505
+ }
2506
+ }
2507
+ },
2508
+ required: ["template"]
2509
+ },
2510
+ isReadOnly: true,
2511
+ async call(input, context) {
2512
+ const { template, params } = input;
2513
+ const title = CANVAS_TITLES[template];
2514
+ if (PHASE_3_TEMPLATES.has(template)) {
2515
+ return {
2516
+ data: {
2517
+ __canvas: true,
2518
+ template,
2519
+ title,
2520
+ templateData: { available: false, message: "This canvas will be available in Phase 3 when analytics APIs are ready." }
2521
+ },
2522
+ displayText: `Canvas template "${title}" is coming soon.`
2523
+ };
2524
+ }
2525
+ if (template === "watch_address") {
2526
+ return {
2527
+ data: {
2528
+ __canvas: true,
2529
+ template,
2530
+ title,
2531
+ templateData: { available: false, address: params?.address ?? null, message: "Watch Address canvas is coming soon." }
2532
+ },
2533
+ displayText: `Canvas template "${title}" is coming soon.`
2534
+ };
2535
+ }
2536
+ const positions = context.serverPositions;
2537
+ const rawRate = positions?.savingsRate ?? 0;
2538
+ const savingsRate = rawRate > 0 && rawRate < 1 ? rawRate * 100 : rawRate > 0 ? rawRate : 4.5;
2539
+ const healthFactor = positions?.healthFactor ?? null;
2540
+ const totalSavings = positions?.savings ?? 0;
2541
+ const totalBorrows = positions?.borrows ?? 0;
2542
+ if (template === "yield_projector") {
2543
+ return {
2544
+ data: {
2545
+ __canvas: true,
2546
+ template,
2547
+ title,
2548
+ templateData: {
2549
+ available: true,
2550
+ initialAmount: totalSavings > 0 ? Math.round(totalSavings) : 1e3,
2551
+ initialApy: savingsRate
2552
+ }
2553
+ },
2554
+ displayText: `Opened Yield Projector. Current USDC deposit rate: ${savingsRate.toFixed(2)}% APY.`
2555
+ };
2556
+ }
2557
+ if (template === "health_simulator") {
2558
+ return {
2559
+ data: {
2560
+ __canvas: true,
2561
+ template,
2562
+ title,
2563
+ templateData: {
2564
+ available: true,
2565
+ initialCollateral: totalSavings > 0 ? Math.round(totalSavings) : 1500,
2566
+ initialDebt: totalBorrows > 0 ? Math.round(totalBorrows) : 500,
2567
+ currentHf: healthFactor
2568
+ }
2569
+ },
2570
+ displayText: `Opened Health Factor Simulator. Current HF: ${healthFactor !== null ? healthFactor.toFixed(2) : "no active position"}.`
2571
+ };
2572
+ }
2573
+ if (template === "dca_planner") {
2574
+ return {
2575
+ data: {
2576
+ __canvas: true,
2577
+ template,
2578
+ title,
2579
+ templateData: {
2580
+ available: true,
2581
+ initialMonthly: 200,
2582
+ initialApy: savingsRate
2583
+ }
2584
+ },
2585
+ displayText: `Opened Savings Plan. Current USDC deposit rate: ${savingsRate.toFixed(2)}% APY.`
2586
+ };
2587
+ }
2588
+ return {
2589
+ data: {
2590
+ __canvas: true,
2591
+ template,
2592
+ title,
2593
+ templateData: { available: false, message: "Unknown template." }
2594
+ },
2595
+ displayText: `Canvas template "${template}" is not yet available.`
2596
+ };
2597
+ }
2598
+ });
2443
2599
  var LLAMA_API2 = "https://api.llama.fi";
2444
2600
  var YIELDS_API2 = "https://yields.llama.fi";
2445
2601
  var COINS_API = "https://coins.llama.fi";
@@ -2724,6 +2880,7 @@ var defillamaSuiProtocolsTool = buildTool({
2724
2880
 
2725
2881
  // src/tools/index.ts
2726
2882
  var READ_TOOLS = [
2883
+ renderCanvasTool,
2727
2884
  balanceCheckTool,
2728
2885
  savingsInfoTool,
2729
2886
  healthCheckTool,
@@ -3117,6 +3274,18 @@ ${summary.join("\n")}`);
3117
3274
  }
3118
3275
  }
3119
3276
  yield toolEvent;
3277
+ if (toolEvent.type === "tool_result" && !toolEvent.isError) {
3278
+ const r = toolEvent.result;
3279
+ if (r && r.__canvas === true) {
3280
+ yield {
3281
+ type: "canvas",
3282
+ template: String(r.template ?? ""),
3283
+ title: String(r.title ?? ""),
3284
+ data: r.templateData ?? null,
3285
+ toolUseId: toolEvent.toolUseId
3286
+ };
3287
+ }
3288
+ }
3120
3289
  if (toolEvent.type === "tool_result") {
3121
3290
  toolResultBlocks.push({
3122
3291
  type: "tool_result",
@@ -4047,6 +4216,6 @@ function sanitizeAnthropicMessages(messages) {
4047
4216
  return merged;
4048
4217
  }
4049
4218
 
4050
- export { AnthropicProvider, 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, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool };
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 };
4051
4220
  //# sourceMappingURL=index.js.map
4052
4221
  //# sourceMappingURL=index.js.map