@t2000/engine 0.28.6 → 0.28.8

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/README.md CHANGED
@@ -87,7 +87,7 @@ QueryEngine.submitMessage()
87
87
 
88
88
  ## Built-in Tools
89
89
 
90
- ### Read Tools (20 — parallel, auto-approved)
90
+ ### Read Tools (29 — parallel, auto-approved)
91
91
 
92
92
  | Tool | Description |
93
93
  |------|-------------|
@@ -111,6 +111,15 @@ QueryEngine.submitMessage()
111
111
  | `defillama_chain_tvl` | Chain TVL rankings |
112
112
  | `defillama_protocol_fees` | Protocol fees/revenue rankings |
113
113
  | `defillama_sui_protocols` | Sui ecosystem protocols — TVL, category, changes |
114
+ | `create_payment_link` | Create a shareable USDC payment link |
115
+ | `list_payment_links` | List payment links with statuses |
116
+ | `cancel_payment_link` | Cancel an active payment link |
117
+ | `create_invoice` | Create a formal invoice with due date and line items |
118
+ | `list_invoices` | List invoices with statuses |
119
+ | `cancel_invoice` | Cancel an unpaid invoice |
120
+ | `toggle_allowance` | Pause or resume agent autonomous spending |
121
+ | `update_daily_limit` | Change the daily USDC spending cap |
122
+ | `update_permissions` | Update which service categories the agent can act on |
114
123
 
115
124
  ### Write Tools (11 — serial, confirmation required)
116
125
 
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
@@ -1985,6 +1985,20 @@ Risks: ${riskFactors.join("; ")}`
1985
1985
  };
1986
1986
  }
1987
1987
  });
1988
+ async function patchAllowance(apiUrl, walletAddress, internalKey, body, signal) {
1989
+ const res = await fetch(`${apiUrl}/api/allowance/${walletAddress}`, {
1990
+ method: "PATCH",
1991
+ headers: {
1992
+ "Content-Type": "application/json",
1993
+ "x-internal-key": internalKey ?? "",
1994
+ "x-sui-address": walletAddress
1995
+ },
1996
+ body: JSON.stringify(body),
1997
+ signal
1998
+ });
1999
+ if (!res.ok) return null;
2000
+ return res.json();
2001
+ }
1988
2002
  var allowanceStatusTool = buildTool({
1989
2003
  name: "allowance_status",
1990
2004
  description: "Check the agent spending allowance status: whether it is enabled, the daily USDC limit, amount spent today, remaining budget, which service categories are permitted, and when the budget resets. Use this when the user asks about their agent budget, spending limits, or autonomous transaction permissions.",
@@ -2035,6 +2049,117 @@ var allowanceStatusTool = buildTool({
2035
2049
  };
2036
2050
  }
2037
2051
  });
2052
+ var toggleAllowanceTool = buildTool({
2053
+ name: "toggle_allowance",
2054
+ description: 'Pause or resume the agent spending allowance. Use when the user says "pause my agent", "disable autonomous spending", "resume my agent", or similar. ALWAYS confirm with the user before calling \u2014 e.g. "Pause agent spending? Your daily limit will be suspended." Only call after explicit confirmation.',
2055
+ inputSchema: z.object({
2056
+ enabled: z.boolean().describe("true to enable agent spending, false to pause it")
2057
+ }),
2058
+ jsonSchema: {
2059
+ type: "object",
2060
+ properties: {
2061
+ enabled: { type: "boolean", description: "true to enable, false to pause" }
2062
+ },
2063
+ required: ["enabled"]
2064
+ },
2065
+ isReadOnly: true,
2066
+ async call(input, context) {
2067
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2068
+ const internalKey = context.env?.AUDRIC_INTERNAL_KEY;
2069
+ if (!apiUrl || !context.walletAddress) {
2070
+ return { data: null, displayText: "Allowance management is not available." };
2071
+ }
2072
+ try {
2073
+ const result = await patchAllowance(apiUrl, context.walletAddress, internalKey, {
2074
+ action: "toggle",
2075
+ enabled: input.enabled
2076
+ }, context.signal);
2077
+ if (!result) return { data: null, displayText: "Failed to update allowance." };
2078
+ const action = input.enabled ? "enabled" : "paused";
2079
+ return {
2080
+ data: result,
2081
+ displayText: `Agent spending ${action}.`
2082
+ };
2083
+ } catch {
2084
+ return { data: null, displayText: "Failed to update allowance." };
2085
+ }
2086
+ }
2087
+ });
2088
+ var updateDailyLimitTool = buildTool({
2089
+ name: "update_daily_limit",
2090
+ description: `Update the agent's daily spending limit in USDC. Use when the user says "set my daily limit to $X", "change my spending cap", or similar. ALWAYS confirm with the user before calling \u2014 show the current limit and the new limit. Only call after explicit confirmation.`,
2091
+ inputSchema: z.object({
2092
+ dailyLimitUsdc: z.number().min(0).max(1e4).describe("New daily limit in USDC (0\u201310000)")
2093
+ }),
2094
+ jsonSchema: {
2095
+ type: "object",
2096
+ properties: {
2097
+ dailyLimitUsdc: { type: "number", description: "New daily spending limit in USDC (0\u201310000)" }
2098
+ },
2099
+ required: ["dailyLimitUsdc"]
2100
+ },
2101
+ isReadOnly: true,
2102
+ async call(input, context) {
2103
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2104
+ const internalKey = context.env?.AUDRIC_INTERNAL_KEY;
2105
+ if (!apiUrl || !context.walletAddress) {
2106
+ return { data: null, displayText: "Allowance management is not available." };
2107
+ }
2108
+ try {
2109
+ const result = await patchAllowance(apiUrl, context.walletAddress, internalKey, {
2110
+ action: "setLimit",
2111
+ dailyLimitUsdc: input.dailyLimitUsdc
2112
+ }, context.signal);
2113
+ if (!result) return { data: null, displayText: "Failed to update daily limit." };
2114
+ return {
2115
+ data: result,
2116
+ displayText: `Daily limit updated to $${input.dailyLimitUsdc.toFixed(2)} USDC.`
2117
+ };
2118
+ } catch {
2119
+ return { data: null, displayText: "Failed to update daily limit." };
2120
+ }
2121
+ }
2122
+ });
2123
+ var updatePermissionsTool = buildTool({
2124
+ name: "update_permissions",
2125
+ description: 'Update which service categories the agent is allowed to act on autonomously. Valid permissions: savings, send, pay, credit, swap, stake. Use when the user says "disable sends", "only allow savings", "enable all services", or similar. ALWAYS show the current permissions and the new permissions before calling. Only call after explicit confirmation.',
2126
+ inputSchema: z.object({
2127
+ permissions: z.array(z.enum(["savings", "send", "pay", "credit", "swap", "stake"])).describe("Full list of enabled permission categories")
2128
+ }),
2129
+ jsonSchema: {
2130
+ type: "object",
2131
+ properties: {
2132
+ permissions: {
2133
+ type: "array",
2134
+ items: { type: "string", enum: ["savings", "send", "pay", "credit", "swap", "stake"] },
2135
+ description: "Full list of enabled permission categories"
2136
+ }
2137
+ },
2138
+ required: ["permissions"]
2139
+ },
2140
+ isReadOnly: true,
2141
+ async call(input, context) {
2142
+ const apiUrl = context.env?.ALLOWANCE_API_URL;
2143
+ const internalKey = context.env?.AUDRIC_INTERNAL_KEY;
2144
+ if (!apiUrl || !context.walletAddress) {
2145
+ return { data: null, displayText: "Allowance management is not available." };
2146
+ }
2147
+ try {
2148
+ const result = await patchAllowance(apiUrl, context.walletAddress, internalKey, {
2149
+ action: "setPermissions",
2150
+ permissions: input.permissions
2151
+ }, context.signal);
2152
+ if (!result) return { data: null, displayText: "Failed to update permissions." };
2153
+ const list = input.permissions.length > 0 ? input.permissions.join(", ") : "none";
2154
+ return {
2155
+ data: result,
2156
+ displayText: `Permissions updated: ${list}.`
2157
+ };
2158
+ } catch {
2159
+ return { data: null, displayText: "Failed to update permissions." };
2160
+ }
2161
+ }
2162
+ });
2038
2163
  var PaymentLinkSchema = z.object({
2039
2164
  amount: z.number().positive().optional().describe("Amount in USDC. Omit for open-amount links."),
2040
2165
  label: z.string().optional().describe('Human-readable label e.g. "Consulting fee March"'),
@@ -2315,6 +2440,161 @@ var listInvoicesTool = buildTool({
2315
2440
  }
2316
2441
  }
2317
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 savingsRate = positions?.savingsRate ?? 4.5;
2538
+ const healthFactor = positions?.healthFactor ?? null;
2539
+ const totalSavings = positions?.savings ?? 0;
2540
+ const totalBorrows = positions?.borrows ?? 0;
2541
+ if (template === "yield_projector") {
2542
+ return {
2543
+ data: {
2544
+ __canvas: true,
2545
+ template,
2546
+ title,
2547
+ templateData: {
2548
+ available: true,
2549
+ initialAmount: totalSavings > 0 ? Math.round(totalSavings) : 1e3,
2550
+ initialApy: savingsRate
2551
+ }
2552
+ },
2553
+ displayText: `Opened Yield Projector. Current USDC deposit rate: ${savingsRate.toFixed(2)}% APY.`
2554
+ };
2555
+ }
2556
+ if (template === "health_simulator") {
2557
+ return {
2558
+ data: {
2559
+ __canvas: true,
2560
+ template,
2561
+ title,
2562
+ templateData: {
2563
+ available: true,
2564
+ initialCollateral: totalSavings > 0 ? Math.round(totalSavings) : 1500,
2565
+ initialDebt: totalBorrows > 0 ? Math.round(totalBorrows) : 500,
2566
+ currentHf: healthFactor
2567
+ }
2568
+ },
2569
+ displayText: `Opened Health Factor Simulator. Current HF: ${healthFactor !== null ? healthFactor.toFixed(2) : "no active position"}.`
2570
+ };
2571
+ }
2572
+ if (template === "dca_planner") {
2573
+ return {
2574
+ data: {
2575
+ __canvas: true,
2576
+ template,
2577
+ title,
2578
+ templateData: {
2579
+ available: true,
2580
+ initialMonthly: 200,
2581
+ initialApy: savingsRate
2582
+ }
2583
+ },
2584
+ displayText: `Opened Savings Plan. Current USDC deposit rate: ${savingsRate.toFixed(2)}% APY.`
2585
+ };
2586
+ }
2587
+ return {
2588
+ data: {
2589
+ __canvas: true,
2590
+ template,
2591
+ title,
2592
+ templateData: { available: false, message: "Unknown template." }
2593
+ },
2594
+ displayText: `Canvas template "${template}" is not yet available.`
2595
+ };
2596
+ }
2597
+ });
2318
2598
  var LLAMA_API2 = "https://api.llama.fi";
2319
2599
  var YIELDS_API2 = "https://yields.llama.fi";
2320
2600
  var COINS_API = "https://coins.llama.fi";
@@ -2599,6 +2879,7 @@ var defillamaSuiProtocolsTool = buildTool({
2599
2879
 
2600
2880
  // src/tools/index.ts
2601
2881
  var READ_TOOLS = [
2882
+ renderCanvasTool,
2602
2883
  balanceCheckTool,
2603
2884
  savingsInfoTool,
2604
2885
  healthCheckTool,
@@ -2619,6 +2900,9 @@ var READ_TOOLS = [
2619
2900
  defillamaProtocolFeesTool,
2620
2901
  defillamaSuiProtocolsTool,
2621
2902
  allowanceStatusTool,
2903
+ toggleAllowanceTool,
2904
+ updateDailyLimitTool,
2905
+ updatePermissionsTool,
2622
2906
  listPaymentLinksTool,
2623
2907
  cancelPaymentLinkTool,
2624
2908
  listInvoicesTool,
@@ -2989,6 +3273,18 @@ ${summary.join("\n")}`);
2989
3273
  }
2990
3274
  }
2991
3275
  yield toolEvent;
3276
+ if (toolEvent.type === "tool_result" && !toolEvent.isError) {
3277
+ const r = toolEvent.result;
3278
+ if (r && r.__canvas === true) {
3279
+ yield {
3280
+ type: "canvas",
3281
+ template: String(r.template ?? ""),
3282
+ title: String(r.title ?? ""),
3283
+ data: r.templateData ?? null,
3284
+ toolUseId: toolEvent.toolUseId
3285
+ };
3286
+ }
3287
+ }
2992
3288
  if (toolEvent.type === "tool_result") {
2993
3289
  toolResultBlocks.push({
2994
3290
  type: "tool_result",
@@ -3919,6 +4215,6 @@ function sanitizeAnthropicMessages(messages) {
3919
4215
  return merged;
3920
4216
  }
3921
4217
 
3922
- 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 };
4218
+ 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 };
3923
4219
  //# sourceMappingURL=index.js.map
3924
4220
  //# sourceMappingURL=index.js.map