@t2000/engine 0.53.4 → 0.54.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
@@ -399,11 +399,19 @@ interface DefiSummary {
399
399
  perProtocol: Partial<Record<DefiProtocol, number>>;
400
400
  pricedAt: number;
401
401
  /**
402
- * `blockvision` — every protocol in `DEFI_PROTOCOLS` responded successfully.
403
- * `partial` — at least one protocol failed; total may under-count.
404
- * `degraded` no API key or every protocol failed; total = 0.
402
+ * `blockvision` — every protocol in `DEFI_PROTOCOLS` responded successfully.
403
+ * `partial` — at least one protocol failed; total may under-count.
404
+ * `partial-stale` fresh fetch returned degraded/partial-zero, but we have a
405
+ * positive value cached within the sticky window
406
+ * (`DEFI_STICKY_TTL_SEC`, default 30min). The numbers are
407
+ * real, just not freshly verified — UI should caveat with
408
+ * "last refresh Nm ago" so the user knows the provenance.
409
+ * Introduced in v0.54 to fix cross-instance SSOT divergence
410
+ * when BlockVision is bursting.
411
+ * `degraded` — no API key, or every protocol failed AND no sticky
412
+ * fallback exists; total = 0.
405
413
  */
406
- source: 'blockvision' | 'partial' | 'degraded';
414
+ source: 'blockvision' | 'partial' | 'partial-stale' | 'degraded';
407
415
  }
408
416
  declare function fetchAddressDefiPortfolio(address: string, apiKey: string | undefined, priceHints?: Record<string, number>): Promise<DefiSummary>;
409
417
  declare function clearPortfolioCache(): void;
@@ -1993,7 +2001,8 @@ declare const balanceCheckTool: Tool<{
1993
2001
  gasReserve: number;
1994
2002
  defi: number;
1995
2003
  defiByProtocol: Partial<Record<"aftermath" | "bluefin" | "cetus" | "haedal" | "scallop" | "suilend" | "suins-staking" | "suistake" | "walrus", number>>;
1996
- defiSource: "blockvision" | "partial" | "degraded";
2004
+ defiSource: "blockvision" | "partial" | "partial-stale" | "degraded";
2005
+ defiPricedAt: number;
1997
2006
  total: number;
1998
2007
  stables: number;
1999
2008
  holdings: any[];
@@ -2423,6 +2432,64 @@ interface WalletCoin {
2423
2432
  */
2424
2433
  declare function fetchWalletCoins(address: string, rpcUrl?: string): Promise<WalletCoin[]>;
2425
2434
 
2435
+ /** Cache entry stored under each address key. */
2436
+ interface DefiCacheEntry {
2437
+ data: DefiSummary;
2438
+ /** Wall-clock ms when this was written — used by the fetcher to compute freshness. */
2439
+ pricedAt: number;
2440
+ }
2441
+ /**
2442
+ * Pluggable cache backend.
2443
+ *
2444
+ * All methods are async because Redis-backed implementations are
2445
+ * inherently async; the in-memory impl wraps in resolved promises.
2446
+ *
2447
+ * Implementations MUST tolerate transport errors gracefully — `get`
2448
+ * should return `null` (not throw) on backend failure so the fetcher
2449
+ * falls through to a fresh BlockVision read instead of erroring the
2450
+ * whole `balance_check` call. `set` should swallow errors (logging is
2451
+ * fine) so a Redis hiccup doesn't break a successful read.
2452
+ */
2453
+ interface DefiCacheStore {
2454
+ /** Returns the cached entry, or `null` if not found / expired / backend error. */
2455
+ get(address: string): Promise<DefiCacheEntry | null>;
2456
+ /** Writes an entry with a TTL in seconds. Errors are swallowed (logged). */
2457
+ set(address: string, entry: DefiCacheEntry, ttlSec: number): Promise<void>;
2458
+ /** Removes the entry for an address. Errors are swallowed. */
2459
+ delete(address: string): Promise<void>;
2460
+ /** Removes all entries. Used by tests and `clearDefiCache()`. */
2461
+ clear(): Promise<void>;
2462
+ }
2463
+ /**
2464
+ * Process-local cache backed by a `Map`. Used as the default when no
2465
+ * other store has been injected via `setDefiCacheStore()`.
2466
+ *
2467
+ * NOT suitable for multi-instance deployments — each Vercel function
2468
+ * instance gets its own Map, which causes the SSOT divergence this
2469
+ * module exists to fix. Audric replaces this at engine init with an
2470
+ * Upstash-backed store; the CLI keeps it.
2471
+ */
2472
+ declare class InMemoryDefiCacheStore implements DefiCacheStore {
2473
+ private readonly store;
2474
+ get(address: string): Promise<DefiCacheEntry | null>;
2475
+ set(address: string, entry: DefiCacheEntry, ttlSec: number): Promise<void>;
2476
+ delete(address: string): Promise<void>;
2477
+ clear(): Promise<void>;
2478
+ }
2479
+ /**
2480
+ * Swap the active DeFi cache store. Call once at engine init from a
2481
+ * runtime that wants a non-default backend (e.g. Audric injecting
2482
+ * `RedisDefiCacheStore`). Idempotent — calling again replaces the
2483
+ * previous store, but does NOT migrate entries; warm cache is lost
2484
+ * on swap. Tests use this to inject a fake/spy store and `resetDefiCacheStore()`
2485
+ * to restore the in-memory default.
2486
+ */
2487
+ declare function setDefiCacheStore(store: DefiCacheStore): void;
2488
+ /** Returns the currently active store. Used by `fetchAddressDefiPortfolio`. */
2489
+ declare function getDefiCacheStore(): DefiCacheStore;
2490
+ /** Restore the default in-memory store. Used by test teardowns. */
2491
+ declare function resetDefiCacheStore(): void;
2492
+
2426
2493
  /**
2427
2494
  * Resolve the audric API base URL from the engine's env shim, falling
2428
2495
  * back to `process.env`. Returns `null` when no override is configured —
@@ -2483,4 +2550,4 @@ declare function fetchAudricHistory(address: string, opts: {
2483
2550
 
2484
2551
  declare const DEFAULT_SYSTEM_PROMPT = "You are Audric \u2014 a financial agent on Sui. Audric is exactly five products: Audric Passport (the trust layer \u2014 Google sign-in, non-custodial wallet, tap-to-confirm consent, sponsored gas \u2014 wraps every other product), Audric Intelligence (you \u2014 the 5-system brain: Agent Harness with 34 tools, Reasoning Engine with 9 guards and 7 skill recipes, Silent Profile, Chain Memory, AdviceLog), Audric Finance (manage money on Sui \u2014 Save via NAVI lending at 3-8% APY USDC, Credit via NAVI borrowing with health factor, Swap via Cetus aggregator across 20+ DEXs at 0.1% fee, Charts for yield/health/portfolio viz), Audric Pay (move money \u2014 send USDC, receive via payment links / invoices / QR; free, global, instant on Sui), and Audric Store (creator marketplace, ships Phase 5 \u2014 say \"coming soon\" if asked). Save, swap, borrow, repay, withdraw, charts \u2192 Audric Finance. Send, receive, payment-link, invoice, QR \u2192 Audric Pay. Your silent context (profile, memory, chain facts, advice log) shapes your replies but never surfaces as a notification \u2014 you act only when the user asks, and every write waits on their tap-to-confirm via Passport. You can also call 41 paid APIs (music, image, research, translation, weather, fulfilment) via MPP micropayments using the pay_api tool \u2014 this is an internal capability, not a promoted product, so only mention it when the user asks for something that needs it.\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- 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## Caption rules (after tool calls)\n- **When a canvas was rendered (`render_canvas` was called, or any tool that auto-renders a card like balance_check / portfolio_analysis / savings_info / health_check / transaction_history): the canvas IS the answer.** Your chat message must NOT restate wallet, savings, debt, holdings, or net-worth numbers \u2014 they are already on screen. Add at most ONE sentence of context, advice, or next step (e.g. \"Your USDC is idle \u2014 consider depositing for ~4.5% APY\"), or say nothing.\n- **When NO canvas was rendered:** lead with the result and quote the actual numbers from the tool. One sentence.\n- **NEVER describe a position as \"no\", \"none\", \"minimal\", \"zero\", or \"inactive\" if the tool result contains a positive value for that field.** The tool result is the source of truth \u2014 never your interior summary. If the canvas shows $100 in savings, you cannot say \"no active savings\" in the caption.\n- **NEVER claim \"no DeFi positions\" when the tool result says the DeFi slice is UNAVAILABLE.** When `balance_check` displayText contains \"DeFi positions: UNAVAILABLE\" or \"DeFi data source unreachable\", the slice is unknown \u2014 say \"DeFi data is currently unavailable\" or omit the mention. Only claim \"no DeFi positions\" when the displayText explicitly omits any DeFi line (i.e. the fetch succeeded with $0 across every covered protocol).\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 NAVI lending APYs, use rates_info; for VOLO liquid staking stats, use volo_stats; for spot token prices, use token_prices.\n- For protocol-level due diligence (TVL, fees, audits, safety) on Sui DeFi protocols, use protocol_deep_dive 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 or USDsui (critical)\n- save_deposit and borrow accept ONLY USDC or USDsui. No other token can be deposited or borrowed.\n- USDC is the canonical default. USDsui is permitted because it has a productive NAVI pool (often a higher APY than USDC). All other holdings (GOLD, SUI, USDT, USDe, ETH, NAVX, WAL) are NOT saveable.\n- When asked \"how much can I save?\":\n - Report saveableUsdc from balance_check (the user's USDC wallet balance \u2014 canonical saveable).\n - If the user also holds USDsui in their wallet, report that separately as \"USDsui (saveable): X.XX\". Do NOT roll the two together \u2014 the LLM must keep the per-asset distinction so the user can pick.\n- When the user says \"save 10 USDC\" \u2192 call save_deposit with asset=\"USDC\". When they say \"save 10 USDsui\" \u2192 call with asset=\"USDsui\". Never silently substitute.\n- When the user says \"save 10\" (no asset) \u2192 call balance_check first and ask which stable they want, OR pick whichever they hold more of with a one-line explanation.\n- \"Best stable to save right now?\" \u2192 call rates_info to compare USDC vs USDsui APY on NAVI; let the user pick.\n- NEVER say a non-saveable token (GOLD, SUI, USDT, etc.) is \"in savings\" or \"earning APY in savings\". Wallet holdings \u2260 savings positions, even for stables we don't accept.\n- If user wants to save a non-saveable token, tell them to swap to USDC or USDsui first. Do NOT auto-chain swap + deposit.\n- Repay symmetry: a USDsui debt MUST be repaid with USDsui (and USDC debt with USDC). When calling repay_debt, pass asset=\"USDsui\" if the borrow is USDsui. If the user asks \"repay my debt\" and savings_info shows borrows in BOTH stables, list both and ask which to repay first. If the user holds the wrong stable, tell them to swap manually \u2014 do NOT auto-chain swap + repay.\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\": token_prices \u2192 calculate amount \u2192 swap_execute.\n- \"Best yield on SUI\": compare rates_info (NAVI lending) + volo_stats (vSUI liquid staking).\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 only accepts USDC or USDsui.\n- \"Is protocol X safe?\" / \"Tell me about NAVI\": protocol_deep_dive with the slug.\n- \"Full account report\" / \"account summary\" / \"give me everything\" / \"complete overview\": triggers the `account_report` recipe \u2014 when the recipe block appears, follow EVERY step including all six tool calls. Each step renders a distinct rich card; skipping a step means a missing card.\n\n## Safety\n- Never encourage risky financial behavior.\n- Warn when health factor < 1.5.\n- All amounts in USDC unless stated otherwise.";
2485
2552
 
2486
- export { type AddressPortfolio, AnthropicProvider, type AnthropicProviderConfig, type AudricHistoryRecord, type AudricPortfolioResult, type BalancePrices, type BalanceResult, BalanceTracker, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, ContextBudget, type ContextBudgetConfig, type ConversationState, type ConversationStateStore, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_GUARD_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYSTEM_PROMPT, type DefiProtocol, type DefiSummary, EarlyToolDispatcher, type EngineConfig, type EngineEvent, type GuardCheckResult, type GuardConfig, type GuardEvent, type GuardInjection, type GuardResult, type GuardRunnerState, type GuardTier, type GuardVerdict, 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 OutputConfig, PERMISSION_PRESETS, type PendingAction, type PendingActionModifiableField, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionOperation, type PermissionResponse, type PermissionRule, type PortfolioCoin, type PositionEntry, type PreflightResult, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type Recipe, type RecipePrerequisite, RecipeRegistry, type RecipeStep, type RecipeStepOnError, RetryTracker, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StateType, type StopReason, type SuiCoinBalance, type SystemBlock, type SystemPrompt, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, type ThinkingConfig, type ThinkingEffort, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolFlags, type ToolJsonSchema, type ToolResult, TxMutex, type UserFinancialProfile, type UserPermissionConfig, WRITE_TOOLS, type WalletCoin, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, claimRewardsTool, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getMcpManager, getModifiableFields, getToolFlags, getWalletAddress, guardArtifactPreview, guardStaleData, hasNaviMcp, healthCheckTool, loadRecipes, microcompact, mppServicesTool, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resolvePermissionTier, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
2553
+ export { type AddressPortfolio, AnthropicProvider, type AnthropicProviderConfig, type AudricHistoryRecord, type AudricPortfolioResult, type BalancePrices, type BalanceResult, BalanceTracker, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, ContextBudget, type ContextBudgetConfig, type ConversationState, type ConversationStateStore, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_GUARD_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYSTEM_PROMPT, type DefiCacheEntry, type DefiCacheStore, type DefiProtocol, type DefiSummary, EarlyToolDispatcher, type EngineConfig, type EngineEvent, type GuardCheckResult, type GuardConfig, type GuardEvent, type GuardInjection, type GuardResult, type GuardRunnerState, type GuardTier, type GuardVerdict, type HealthFactorResult, InMemoryDefiCacheStore, 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 OutputConfig, PERMISSION_PRESETS, type PendingAction, type PendingActionModifiableField, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionOperation, type PermissionResponse, type PermissionRule, type PortfolioCoin, type PositionEntry, type PreflightResult, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type Recipe, type RecipePrerequisite, RecipeRegistry, type RecipeStep, type RecipeStepOnError, RetryTracker, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StateType, type StopReason, type SuiCoinBalance, type SystemBlock, type SystemPrompt, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, type ThinkingConfig, type ThinkingEffort, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolFlags, type ToolJsonSchema, type ToolResult, TxMutex, type UserFinancialProfile, type UserPermissionConfig, WRITE_TOOLS, type WalletCoin, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, claimRewardsTool, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getMcpManager, getModifiableFields, getToolFlags, getWalletAddress, guardArtifactPreview, guardStaleData, hasNaviMcp, healthCheckTool, loadRecipes, microcompact, mppServicesTool, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resolvePermissionTier, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
package/dist/index.js CHANGED
@@ -496,6 +496,42 @@ async function fetchWalletCoins(address, rpcUrl) {
496
496
  });
497
497
  }
498
498
 
499
+ // src/defi-cache.ts
500
+ var InMemoryDefiCacheStore = class {
501
+ store = /* @__PURE__ */ new Map();
502
+ async get(address) {
503
+ const slot = this.store.get(address.toLowerCase());
504
+ if (!slot) return null;
505
+ if (Date.now() >= slot.expiresAt) {
506
+ this.store.delete(address.toLowerCase());
507
+ return null;
508
+ }
509
+ return slot.entry;
510
+ }
511
+ async set(address, entry, ttlSec) {
512
+ this.store.set(address.toLowerCase(), {
513
+ entry,
514
+ expiresAt: Date.now() + ttlSec * 1e3
515
+ });
516
+ }
517
+ async delete(address) {
518
+ this.store.delete(address.toLowerCase());
519
+ }
520
+ async clear() {
521
+ this.store.clear();
522
+ }
523
+ };
524
+ var activeStore = new InMemoryDefiCacheStore();
525
+ function setDefiCacheStore(store) {
526
+ activeStore = store;
527
+ }
528
+ function getDefiCacheStore() {
529
+ return activeStore;
530
+ }
531
+ function resetDefiCacheStore() {
532
+ activeStore = new InMemoryDefiCacheStore();
533
+ }
534
+
499
535
  // src/blockvision-prices.ts
500
536
  var BLOCKVISION_BASE = "https://api.blockvision.org/v2/sui";
501
537
  var PORTFOLIO_TIMEOUT_MS = 4e3;
@@ -723,8 +759,10 @@ function parseNumberOrNull(input) {
723
759
  return Number.isFinite(n) ? n : null;
724
760
  }
725
761
  var DEFI_PORTFOLIO_TIMEOUT_MS = 4e3;
726
- var DEFI_CACHE_TTL_MS = 6e4;
727
- var DEFI_PARTIAL_CACHE_TTL_MS = 15e3;
762
+ var DEFI_FRESH_TTL_MS_BLOCKVISION = 6e4;
763
+ var DEFI_FRESH_TTL_MS_PARTIAL = 15e3;
764
+ var DEFI_FRESH_TTL_MS_PARTIAL_STALE = 0;
765
+ var DEFI_STICKY_TTL_SEC = 30 * 60;
728
766
  var DEFI_PROTOCOLS = [
729
767
  "aftermath",
730
768
  "bluefin",
@@ -741,8 +779,26 @@ var USDC_TYPE_FULL = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846
741
779
  var BLUE_TYPE_FULL = "0xe1b45a0e641b9955a20aa0ad1c1f4ad86aad8afb07296d4085e349a50e90bdca::blue::BLUE";
742
780
  var WAL_TYPE_FULL = "0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL";
743
781
  var NS_TYPE_FULL = "0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178::ns::NS";
744
- var defiCache = /* @__PURE__ */ new Map();
745
782
  var defiInflight = /* @__PURE__ */ new Map();
783
+ function freshTtlForSource(source) {
784
+ switch (source) {
785
+ case "blockvision":
786
+ return DEFI_FRESH_TTL_MS_BLOCKVISION;
787
+ case "partial":
788
+ return DEFI_FRESH_TTL_MS_PARTIAL;
789
+ case "partial-stale":
790
+ return DEFI_FRESH_TTL_MS_PARTIAL_STALE;
791
+ case "degraded":
792
+ return 0;
793
+ }
794
+ }
795
+ async function safeStoreSet(store, address, entry) {
796
+ try {
797
+ await store.set(address, entry, DEFI_STICKY_TTL_SEC);
798
+ } catch (err) {
799
+ console.warn("[defi] cache set failed (non-fatal):", err);
800
+ }
801
+ }
746
802
  var warnedMissingApiKey = false;
747
803
  async function fetchAddressDefiPortfolio(address, apiKey, priceHints = {}) {
748
804
  if (!apiKey || apiKey.trim().length === 0) {
@@ -754,9 +810,21 @@ async function fetchAddressDefiPortfolio(address, apiKey, priceHints = {}) {
754
810
  }
755
811
  return { totalUsd: 0, perProtocol: {}, pricedAt: Date.now(), source: "degraded" };
756
812
  }
813
+ const store = getDefiCacheStore();
757
814
  const now = Date.now();
758
- const cached = defiCache.get(address);
759
- if (cached && now - cached.ts < DEFI_CACHE_TTL_MS) return cached.data;
815
+ let cachedEntry = null;
816
+ try {
817
+ cachedEntry = await store.get(address);
818
+ } catch (err) {
819
+ console.warn("[defi] cache get failed (continuing as cache miss):", err);
820
+ }
821
+ if (cachedEntry) {
822
+ const ageMs = now - cachedEntry.pricedAt;
823
+ const freshTtlMs = freshTtlForSource(cachedEntry.data.source);
824
+ if (ageMs < freshTtlMs) {
825
+ return cachedEntry.data;
826
+ }
827
+ }
760
828
  let inflight = defiInflight.get(address);
761
829
  if (inflight) return inflight;
762
830
  inflight = (async () => {
@@ -813,21 +881,28 @@ async function fetchAddressDefiPortfolio(address, apiKey, priceHints = {}) {
813
881
  }
814
882
  }
815
883
  if (totalUsd < 0) totalUsd = 0;
884
+ const fetchedAt = Date.now();
816
885
  const summary = {
817
886
  totalUsd,
818
887
  perProtocol,
819
- pricedAt: Date.now(),
888
+ pricedAt: fetchedAt,
820
889
  source: failures === DEFI_PROTOCOLS.length ? "degraded" : failures > 0 ? "partial" : "blockvision"
821
890
  };
891
+ const cachedPositive = cachedEntry && cachedEntry.data.totalUsd > 0 && now - cachedEntry.pricedAt < DEFI_STICKY_TTL_SEC * 1e3;
822
892
  if (summary.source === "blockvision") {
823
- defiCache.set(address, { data: summary, ts: Date.now() });
824
- } else if (summary.source === "partial") {
825
- defiCache.set(address, {
826
- data: summary,
827
- // Subtract from `now` so cache TTL elapses to (TTL - PARTIAL_AGE_MS)
828
- // from a fresh-cache caller's perspective. Effective TTL = 15s.
829
- ts: Date.now() - (DEFI_CACHE_TTL_MS - DEFI_PARTIAL_CACHE_TTL_MS)
830
- });
893
+ await safeStoreSet(store, address, { data: summary, pricedAt: fetchedAt });
894
+ return summary;
895
+ }
896
+ if (summary.source === "partial" && summary.totalUsd > 0) {
897
+ await safeStoreSet(store, address, { data: summary, pricedAt: fetchedAt });
898
+ return summary;
899
+ }
900
+ if (cachedPositive) {
901
+ const stale = {
902
+ ...cachedEntry.data,
903
+ source: "partial-stale"
904
+ };
905
+ return stale;
831
906
  }
832
907
  return summary;
833
908
  } finally {
@@ -1405,6 +1480,10 @@ var balanceCheckTool = buildTool({
1405
1480
  defi: defi2.totalUsd,
1406
1481
  defiByProtocol: defi2.perProtocol,
1407
1482
  defiSource: defi2.source,
1483
+ // [v0.54] Forward the DeFi entry's pricedAt so the BalanceCard
1484
+ // can render "cached Nm ago" when source === 'partial-stale'.
1485
+ // Always populated; consumers ignore unless source is stale.
1486
+ defiPricedAt: defi2.pricedAt,
1408
1487
  total: availableUsd + savings + gasReserveUsd2 + pendingRewardsUsd + defi2.totalUsd - debt,
1409
1488
  stables: stablesUsd,
1410
1489
  holdings: visibleHoldings,
@@ -1420,6 +1499,10 @@ var balanceCheckTool = buildTool({
1420
1499
  if (defi2.source === "degraded") {
1421
1500
  return ' DeFi positions (Bluefin / Suilend / Cetus / etc.): UNAVAILABLE \u2014 DeFi data source is currently unreachable. Do NOT assert "no DeFi positions"; tell the user this slice is temporarily unknown and the total above EXCLUDES DeFi.';
1422
1501
  }
1502
+ if (defi2.source === "partial-stale" && defi2.totalUsd > 0) {
1503
+ const ageMin = Math.round((Date.now() - defi2.pricedAt) / 6e4);
1504
+ return ` Other DeFi positions (LPs/staking/lending across ${Object.keys(defi2.perProtocol).join("/")}): $${defi2.totalUsd.toFixed(2)} (last refresh ${ageMin}m ago \u2014 live BlockVision call failed, using cached value).`;
1505
+ }
1423
1506
  if (defi2.totalUsd > 0) {
1424
1507
  const partialNote = defi2.source === "partial" ? " (partial \u2014 one or more protocols failed; value may under-count)" : "";
1425
1508
  return ` Other DeFi positions (LPs/staking/lending across ${Object.keys(defi2.perProtocol).join("/")}): $${defi2.totalUsd.toFixed(2)}${partialNote}.`;
@@ -1467,6 +1550,10 @@ var balanceCheckTool = buildTool({
1467
1550
  if (defi.source === "degraded") {
1468
1551
  return ' DeFi positions: UNAVAILABLE \u2014 data source unreachable. Do NOT claim "no DeFi positions"; report this slice as temporarily unknown and the total above EXCLUDES DeFi.';
1469
1552
  }
1553
+ if (defi.source === "partial-stale" && defi.totalUsd > 0) {
1554
+ const ageMin = Math.round((Date.now() - defi.pricedAt) / 6e4);
1555
+ return ` Other DeFi positions (LPs/staking/lending across ${Object.keys(defi.perProtocol).join("/")}): $${defi.totalUsd.toFixed(2)} (last refresh ${ageMin}m ago \u2014 live BlockVision call failed, using cached value).`;
1556
+ }
1470
1557
  if (defi.totalUsd > 0) {
1471
1558
  const partialNote = defi.source === "partial" ? " (partial \u2014 one or more protocols failed; value may under-count)" : "";
1472
1559
  return ` Other DeFi positions (LPs/staking/lending across ${Object.keys(defi.perProtocol).join("/")}): $${defi.totalUsd.toFixed(2)}${partialNote}.`;
@@ -1487,6 +1574,8 @@ var balanceCheckTool = buildTool({
1487
1574
  defi: defi.totalUsd,
1488
1575
  defiByProtocol: defi.perProtocol,
1489
1576
  defiSource: defi.source,
1577
+ // [v0.54] Same staleness provenance as the MCP path above.
1578
+ defiPricedAt: defi.pricedAt,
1490
1579
  total: sdkTotal,
1491
1580
  stables: stablesTotal,
1492
1581
  holdings: holdingsArr,
@@ -7600,6 +7689,6 @@ function sanitizeAnthropicMessages(messages) {
7600
7689
  return merged;
7601
7690
  }
7602
7691
 
7603
- export { AnthropicProvider, BalanceTracker, CANVAS_TEMPLATES, ContextBudget, CostTracker, DEFAULT_GUARD_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYSTEM_PROMPT, EarlyToolDispatcher, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, NaviTools, PERMISSION_PRESETS, QueryEngine, READ_TOOLS, RecipeRegistry, RetryTracker, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TxMutex, WRITE_TOOLS, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, claimRewardsTool, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getMcpManager, getModifiableFields, getToolFlags, getWalletAddress, guardArtifactPreview, guardStaleData, hasNaviMcp, healthCheckTool, loadRecipes, microcompact, mppServicesTool, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resolvePermissionTier, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
7692
+ export { AnthropicProvider, BalanceTracker, CANVAS_TEMPLATES, ContextBudget, CostTracker, DEFAULT_GUARD_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYSTEM_PROMPT, EarlyToolDispatcher, InMemoryDefiCacheStore, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, NaviTools, PERMISSION_PRESETS, QueryEngine, READ_TOOLS, RecipeRegistry, RetryTracker, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TxMutex, WRITE_TOOLS, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, claimRewardsTool, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getMcpManager, getModifiableFields, getToolFlags, getWalletAddress, guardArtifactPreview, guardStaleData, hasNaviMcp, healthCheckTool, loadRecipes, microcompact, mppServicesTool, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resolvePermissionTier, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
7604
7693
  //# sourceMappingURL=index.js.map
7605
7694
  //# sourceMappingURL=index.js.map