@t2000/engine 0.46.16 → 0.47.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @t2000/engine
2
2
 
3
- Agent engine for conversational finance — implements **Audric Intelligence** (the moat behind the Audric consumer product). Five systems work together: Agent Harness (40 tools), Reasoning Engine (9 guards across 3 priority tiers + 7 YAML skill recipes), Silent Profile, Chain Memory, and AdviceLog. Every action it triggers waits on Audric Passport's tap-to-confirm.
3
+ Agent engine for conversational finance — implements **Audric Intelligence** (the moat behind the Audric consumer product). Five systems work together: Agent Harness (34 tools — 23 read, 11 write), Reasoning Engine (9 guards across 3 priority tiers + 7 YAML skill recipes), Silent Profile, Chain Memory, and AdviceLog. Every action it triggers waits on Audric Passport's tap-to-confirm.
4
4
 
5
5
  QueryEngine orchestrates LLM conversations, financial tools, user confirmations, and MCP integrations into a single async-generator loop.
6
6
 
@@ -75,8 +75,9 @@ QueryEngine.submitMessage()
75
75
  | `navi-config.ts` | `NAVI_MCP_CONFIG`, `NaviTools` | NAVI MCP server configuration |
76
76
  | `navi-transforms.ts` | `transformRates`, `transformBalance`, ... | Raw MCP response → engine types |
77
77
  | `navi-reads.ts` | `fetchRates`, `fetchBalance`, ... | Composite MCP read functions |
78
- | `defillama-prices.ts` | `fetchTokenPrices`, `clearPriceCache` | Batch USD prices from DefiLlama (single price source) |
79
- | `tools/defillama.ts` | 7 DefiLlama tools | Yield pools, protocol info, token prices, price changes, chain TVL, fees, Sui protocols |
78
+ | `blockvision-prices.ts` | `fetchAddressPortfolio`, `fetchTokenPrices`, `clearPortfolioCache`, `clearPortfolioCacheFor`, `clearPriceMapCache` | BlockVision Indexer REST: full wallet portfolio + multi-token USD prices (Sui RPC + hardcoded-stable degraded fallback) |
79
+ | `tools/protocol-deep-dive.ts` | `protocolDeepDiveTool` | DefiLlama protocol metadata (TVL, fees, audits, safety score) lone production dependency on `api.llama.fi` post-Day-3 |
80
+ | `tools/token-prices.ts` | `tokenPricesTool` | BlockVision-backed multi-token spot price + 24h change (replaces deleted `defillama_token_prices` / `defillama_price_change`) |
80
81
  | `tools/swap-quote.ts` | `swapQuoteTool` | Preview swap route + price impact (read-only) |
81
82
  | `tools/swap.ts` | `swapExecuteTool` | Cetus Aggregator multi-DEX swap |
82
83
  | `tools/volo-stats.ts` | `voloStatsTool` | VOLO liquid staking stats (vSUI/SUI rate, APY, TVL) |
@@ -87,11 +88,11 @@ QueryEngine.submitMessage()
87
88
 
88
89
  ## Built-in Tools
89
90
 
90
- ### Read Tools (29 — parallel, auto-approved)
91
+ ### Read Tools (23 — parallel, auto-approved)
91
92
 
92
93
  | Tool | Description |
93
94
  |------|-------------|
94
- | `balance_check` | Available, savings, debt, rewards, gas reserve (DefiLlama pricing) |
95
+ | `balance_check` | Available, savings, debt, rewards, gas reserve (BlockVision pricing, Sui RPC fallback) |
95
96
  | `savings_info` | Positions, earnings, fund status |
96
97
  | `health_check` | Health factor with risk assessment |
97
98
  | `rates_info` | Current supply/borrow APYs |
@@ -101,15 +102,9 @@ QueryEngine.submitMessage()
101
102
  | `swap_quote` | Preview swap route, output amount, and price impact (no execution) |
102
103
  | `volo_stats` | VOLO liquid staking stats — vSUI/SUI rate, APY, TVL |
103
104
  | `portfolio_analysis` | Portfolio breakdown with diversification insights |
104
- | `protocol_deep_dive` | Deep protocol analysis — TVL, yields, risks, alternatives |
105
+ | `protocol_deep_dive` | Deep protocol analysis — TVL, yields, risks, alternatives (lone surviving DefiLlama dependency) |
105
106
  | `mpp_services` | Browse available MPP gateway services and endpoints |
106
- | `defillama_yield_pools` | Top yield pools by APY, filterable by chain |
107
- | `defillama_protocol_info` | Protocol TVL, category, chains |
108
- | `defillama_token_prices` | Current USD prices for Sui tokens |
109
- | `defillama_price_change` | Token price % change over period |
110
- | `defillama_chain_tvl` | Chain TVL rankings |
111
- | `defillama_protocol_fees` | Protocol fees/revenue rankings |
112
- | `defillama_sui_protocols` | Sui ecosystem protocols — TVL, category, changes |
107
+ | `token_prices` | Current USD prices for Sui tokens (BlockVision; optional 24h change). Replaces deleted `defillama_token_prices` and `defillama_price_change`. |
113
108
  | `create_payment_link` | Create a shareable USDC payment link |
114
109
  | `list_payment_links` | List payment links with statuses |
115
110
  | `cancel_payment_link` | Cancel an active payment link |
@@ -145,6 +140,14 @@ QueryEngine.submitMessage()
145
140
  > `create_schedule`, `list_schedules`, `cancel_schedule` (DCA can't execute without user
146
141
  > online to sign), `pattern_status`, `pause_pattern` (pattern proposals removed; classifiers
147
142
  > kept as pure functions).
143
+ >
144
+ > **v1.4 BlockVision swap (April 2026):** Removed 7 `defillama_*` read tools —
145
+ > `defillama_token_prices`, `defillama_price_change`, `defillama_yield_pools`,
146
+ > `defillama_protocol_info`, `defillama_chain_tvl`, `defillama_protocol_fees`,
147
+ > `defillama_sui_protocols`. Added 1 — `token_prices` (BlockVision-backed). `balance_check`
148
+ > and `portfolio_analysis` rewired to BlockVision Indexer REST API for sub-500ms portfolio
149
+ > fetches. `protocol_deep_dive` retains its DefiLlama dependency (narrow scope, no
150
+ > equivalent on BlockVision). Net: 23 reads + 11 writes = 34 tools.
148
151
 
149
152
  ## Audric 2.0 Engine Features
150
153
 
@@ -177,23 +180,55 @@ Write tool permission resolved dynamically via `resolvePermissionTier(operation,
177
180
 
178
181
  ```typescript
179
182
  interface EngineConfig {
180
- provider: LLMProvider; // Required — LLM provider instance
181
- agent?: unknown; // T2000 SDK instance (for tool execution)
182
- mcpManager?: unknown; // McpClientManager (MCP-first reads)
183
- walletAddress?: string; // User's Sui address (for MCP reads)
184
- tools?: Tool[]; // Custom tool set (defaults to getDefaultTools())
185
- systemPrompt?: string; // Override default Audric prompt
186
- model?: string; // LLM model override
187
- maxTurns?: number; // Max conversation turns (default: 10)
188
- maxTokens?: number; // Max tokens per response (default: 4096)
183
+ // Core
184
+ provider: LLMProvider; // Required LLM provider instance
185
+ agent?: unknown; // T2000 SDK instance (for tool execution)
186
+ mcpManager?: unknown; // McpClientManager (MCP-first reads)
187
+ walletAddress?: string; // User's Sui address populated into onAutoExecuted
188
+ suiRpcUrl?: string; // Sui JSON-RPC URL for direct chain queries
189
+ tools?: Tool[]; // Custom tool set (defaults to getDefaultTools())
190
+ systemPrompt?: string | SystemBlock[]; // Override default Audric prompt
191
+ model?: string; // LLM model override
192
+ maxTurns?: number; // Max conversation turns (default: 10)
193
+ maxTokens?: number; // Max tokens per response (default: 4096)
194
+
195
+ // [v1.4 BlockVision] Pricing + portfolio
196
+ blockvisionApiKey?: string; // BlockVision Indexer key — degrades to Sui RPC if absent
197
+ portfolioCache?: Map<string, AddressPortfolio>; // Per-request portfolio memoisation across read tools
198
+
199
+ // Reasoning engine
200
+ guards?: GuardConfig; // Guard runner (RE-2.2)
201
+ recipes?: RecipeRegistry; // YAML skill recipes (RE-3.1)
202
+ contextBudget?: ContextBudgetConfig; // 200k limit, compaction trigger (RE-3.3)
203
+ contextSummarizer?: (msgs) => Promise<string>; // LLM summarizer fallback for compaction
204
+ thinking?: ThinkingConfig; // Adaptive / extended thinking
205
+ outputConfig?: OutputConfig; // Effort hint
206
+
207
+ // Permissions + state
208
+ permissionConfig?: UserPermissionConfig; // USD-threshold write gating (B.4)
209
+ priceCache?: Map<string, number>; // Symbol → USD for permission resolution
210
+ contacts?: ReadonlyArray<{ name: string; address: string }>; // Trusted send-transfer recipients
211
+ sessionSpendUsd?: number; // Cumulative session auto-execute total
212
+
213
+ // Hooks
214
+ onAutoExecuted?: (info: { // [v1.4] Fired after auto-tier write succeeds
215
+ toolName: string;
216
+ usdValue: number;
217
+ walletAddress?: string; // Populated from config.walletAddress for cache invalidation
218
+ }) => void | Promise<void>;
219
+ onGuardFired?: (guard: GuardMetric) => void; // [v1.4 Item 4] Per-guard observation hook
220
+ postWriteRefresh?: Record<string, string[]>; // [v1.5] Auto-rerun reads after a successful write
221
+
189
222
  costTracker?: {
190
- budgetLimitUsd?: number; // Kill switch at USD threshold
223
+ budgetLimitUsd?: number; // Kill switch at USD threshold
191
224
  inputCostPerToken?: number;
192
225
  outputCostPerToken?: number;
193
226
  };
194
227
  }
195
228
  ```
196
229
 
230
+ > See `packages/engine/src/types.ts` for the canonical interface — additional internal fields and full JSDoc.
231
+
197
232
  ## Event Types
198
233
 
199
234
  The `submitMessage()` async generator yields `EngineEvent`:
@@ -205,7 +240,7 @@ The `submitMessage()` async generator yields `EngineEvent`:
205
240
  | `thinking_done` | — | Extended thinking complete |
206
241
  | `tool_start` | `toolName`, `toolUseId`, `input` | Tool execution begins |
207
242
  | `tool_result` | `toolName`, `toolUseId`, `result`, `isError` | Tool execution completes |
208
- | `pending_action` | `action` (PendingAction) | Write tool awaiting client-side execution |
243
+ | `pending_action` | `action` (PendingAction with `attemptId`, `toolUseId`, `turnIndex`, `name`, `input`) | Write tool awaiting client-side execution. `attemptId` is a per-yield UUID — hosts persist it on TurnMetrics and key the resume `updateMany` on it (avoids ambiguous `(sessionId, turnIndex)` updates) |
209
244
  | `canvas` | `html` | Interactive HTML visualization from `render_canvas` |
210
245
  | `turn_complete` | `stopReason` | Conversation turn finished |
211
246
  | `usage` | `inputTokens`, `outputTokens`, `cacheReadTokens?`, `cacheWriteTokens?` | Token usage report |
package/dist/index.d.ts CHANGED
@@ -338,6 +338,62 @@ declare function extractConversationText(messages: Array<{
338
338
  recentUserText: string;
339
339
  };
340
340
 
341
+ interface PortfolioCoin {
342
+ coinType: string;
343
+ symbol: string;
344
+ decimals: number;
345
+ /** Raw on-chain amount (string to preserve precision). */
346
+ balance: string;
347
+ /** USD spot price; `null` when not available (long-tail, degraded mode). */
348
+ price: number | null;
349
+ /** balance/10^decimals * price; `null` when price is `null`. */
350
+ usdValue: number | null;
351
+ }
352
+ interface AddressPortfolio {
353
+ coins: PortfolioCoin[];
354
+ totalUsd: number;
355
+ pricedAt: number;
356
+ source: 'blockvision' | 'sui-rpc-degraded';
357
+ }
358
+ /**
359
+ * One-shot wallet portfolio fetcher. BlockVision returns balances + USD
360
+ * prices in a single call; on failure we degrade to a Sui-RPC coin fetch
361
+ * with hardcoded stablecoin pricing. Memoised in-process for `CACHE_TTL_MS`
362
+ * keyed by `address` so back-to-back tool calls inside the same chat
363
+ * session (balance_check + portfolio_analysis) share the same response.
364
+ */
365
+ declare function fetchAddressPortfolio(address: string, apiKey: string | undefined, fallbackRpcUrl?: string): Promise<AddressPortfolio>;
366
+ /**
367
+ * Multi-token price lookup. Returns a map of coinType → `{ price, change24h }`
368
+ * with the `change24h` field populated when BlockVision returns it.
369
+ * Hardcoded stable allow-list short-circuits before the network call so
370
+ * USDC/USDT lookups don't pay the BlockVision RTT. Chunks transparently
371
+ * (BlockVision caps `tokenIds` at 10 per call). Cached in-process for
372
+ * `CACHE_TTL_MS` with merge-on-miss semantics — a cache containing 8 of 10
373
+ * requested coins fetches only the missing 2 instead of throwing the
374
+ * whole map away.
375
+ */
376
+ declare function fetchTokenPrices(coinTypes: string[], apiKey: string | undefined): Promise<Record<string, {
377
+ price: number;
378
+ change24h?: number;
379
+ }>>;
380
+ declare function clearPortfolioCache(): void;
381
+ /**
382
+ * [v1.4 — Day 2.5] Per-address invalidator. The module-level
383
+ * `portfolioCache` carries a 60s TTL — long enough to outlive a
384
+ * `save_deposit` / `swap_execute` / etc. plus the engine's 1.5s
385
+ * Sui-RPC-indexer-lag delay, so without explicit invalidation
386
+ * `runPostWriteRefresh` would re-fetch the *cached pre-write
387
+ * snapshot*. Engine calls this from `runPostWriteRefresh` right
388
+ * before the lag-delay so the next `fetchAddressPortfolio` for the
389
+ * affected address is forced to hit BlockVision again.
390
+ *
391
+ * No-op when `address` doesn't match a cached entry — cheap to call
392
+ * unconditionally on every write.
393
+ */
394
+ declare function clearPortfolioCacheFor(address: string): void;
395
+ declare function clearPriceMapCache(): void;
396
+
341
397
  /**
342
398
  * USD-aware permission resolution for write tools.
343
399
  *
@@ -614,6 +670,18 @@ interface PendingAction {
614
670
  * `apps/web/app/api/engine/resume/route.ts` `updateMany` clause.
615
671
  */
616
672
  turnIndex: number;
673
+ /**
674
+ * [v1.4.2 — Day 3 / Spec Item 3] Per-yield random identifier (UUID v4)
675
+ * stamped at the moment the engine emits this `pending_action`. Hosts
676
+ * persist it on the `TurnMetrics` row at chat-time and key the resume
677
+ * route's `updateMany` on it instead of `(sessionId, turnIndex)` — that
678
+ * pair is ambiguous when the same turn yields a second pending action
679
+ * (e.g. user edits → re-yield) or when a backfill leaves multiple rows
680
+ * matching the pair, which is exactly the false-resolution bug Item 3
681
+ * exists to kill. Also survives session persistence so the resume call
682
+ * can read it back from the rehydrated `PendingAction`.
683
+ */
684
+ attemptId: string;
617
685
  }
618
686
  /**
619
687
  * Response from the client when resolving a pending action.
@@ -651,6 +719,25 @@ interface ToolContext {
651
719
  * value would exceed the limit. Optional; omitted = unbounded.
652
720
  */
653
721
  sessionSpendUsd?: number;
722
+ /**
723
+ * [v1.4 BlockVision] Server-only BlockVision Indexer API key. Threaded
724
+ * through from the host (`audric/apps/web` reads
725
+ * `process.env.BLOCKVISION_API_KEY`). Forwarded to
726
+ * `fetchAddressPortfolio` / `fetchTokenPrices` in `blockvision-prices.ts`.
727
+ * When undefined / empty the price feed degrades to Sui RPC + the
728
+ * hardcoded stable allow-list — wallets still render but non-stable
729
+ * USD values are reported as `null`.
730
+ */
731
+ blockvisionApiKey?: string;
732
+ /**
733
+ * [v1.4 BlockVision] Per-request memoization of the BlockVision portfolio
734
+ * response. Keyed by Sui address. Multiple read tools (`balance_check`,
735
+ * `portfolio_analysis`) inside the same chat turn re-hit the same address;
736
+ * sharing this Map across them avoids a second 200–500ms BlockVision RTT.
737
+ * The `blockvision-prices` module also has its own TTL cache, so this is
738
+ * primarily a fast-path optimisation rather than a correctness primitive.
739
+ */
740
+ portfolioCache?: Map<string, AddressPortfolio>;
654
741
  }
655
742
  interface ServerPositionData {
656
743
  savings: number;
@@ -800,15 +887,34 @@ interface EngineConfig {
800
887
  * enforce `autonomousDailyLimit`.
801
888
  */
802
889
  sessionSpendUsd?: number;
890
+ /**
891
+ * [v1.4 BlockVision] Server-only BlockVision Indexer API key. Forwarded
892
+ * verbatim into `ToolContext.blockvisionApiKey` for read tools that hit
893
+ * `api.blockvision.org` (`balance_check`, `portfolio_analysis`,
894
+ * `token_prices`). When omitted, those tools degrade gracefully to a
895
+ * Sui-RPC + hardcoded-stable fallback — see `blockvision-prices.ts`.
896
+ */
897
+ blockvisionApiKey?: string;
898
+ /**
899
+ * [v1.4 BlockVision] Per-request portfolio cache shared across read
900
+ * tools in the same chat turn. Forwarded into `ToolContext.portfolioCache`.
901
+ */
902
+ portfolioCache?: Map<string, AddressPortfolio>;
803
903
  /**
804
904
  * [v1.4] Fired after a write tool successfully auto-executes (no
805
905
  * confirmation required). Hosts use this to persist cumulative spend in
806
- * Redis. Errors are caught the tool result is never blocked by a failure
807
- * here.
906
+ * Redis and (post-v1.4 BlockVision swap) invalidate cross-session caches
907
+ * keyed by the user's wallet address. Errors are caught — the tool
908
+ * result is never blocked by a failure here.
909
+ *
910
+ * The `walletAddress` field is populated from the engine's
911
+ * `config.walletAddress`; it's absent only on unauthenticated engines
912
+ * (which never auto-execute a real write).
808
913
  */
809
914
  onAutoExecuted?: (info: {
810
915
  toolName: string;
811
916
  usdValue: number;
917
+ walletAddress?: string;
812
918
  }) => void | Promise<void>;
813
919
  /**
814
920
  * [v1.4 Item 4] Per-guard observation hook. Forwarded to `runGuards`
@@ -980,6 +1086,8 @@ declare class QueryEngine {
980
1086
  private readonly sessionSpendUsd;
981
1087
  private readonly onAutoExecuted;
982
1088
  private readonly onGuardFired;
1089
+ private readonly blockvisionApiKey;
1090
+ private readonly portfolioCache;
983
1091
  private readonly postWriteRefresh;
984
1092
  private matchedRecipe;
985
1093
  private messages;
@@ -2100,6 +2208,7 @@ interface PortfolioResult {
2100
2208
  savingsApy?: number;
2101
2209
  dailyEarning?: number;
2102
2210
  weekChange?: WeekChange;
2211
+ priceSource: AddressPortfolio['source'];
2103
2212
  }
2104
2213
  declare const portfolioAnalysisTool: Tool<{
2105
2214
  address?: string | undefined;
@@ -2168,66 +2277,20 @@ declare const activitySummaryTool: Tool<{
2168
2277
  period?: "month" | "year" | "all" | "week" | undefined;
2169
2278
  }, ActivitySummary>;
2170
2279
 
2171
- declare const defillamaYieldPoolsTool: Tool<{
2172
- stableOnly?: boolean | undefined;
2173
- limit?: number | undefined;
2174
- chain?: string | undefined;
2175
- project?: string | undefined;
2176
- minTvl?: number | undefined;
2177
- }, Record<string, unknown> | unknown[]>;
2178
- declare const defillamaProtocolInfoTool: Tool<{
2179
- name: string;
2180
- }, {
2181
- name: string;
2182
- category: string;
2183
- chains: string[];
2184
- tvl: number;
2185
- change1d: number | undefined;
2186
- change7d: number | undefined;
2187
- url: string;
2188
- description: string | undefined;
2189
- }>;
2190
- declare const defillamaTokenPricesTool: Tool<{
2280
+ declare const tokenPricesTool: Tool<{
2191
2281
  coinTypes: string[];
2192
- }, {
2282
+ include24hChange?: boolean | undefined;
2283
+ }, ({
2193
2284
  coinType: string;
2194
2285
  symbol: string;
2195
2286
  price: number;
2196
- }[]>;
2197
- declare const defillamaPriceChangeTool: Tool<{
2287
+ change24h?: number;
2288
+ } | {
2198
2289
  coinType: string;
2199
- period?: "1h" | "24h" | "7d" | "30d" | undefined;
2200
- }, {
2201
2290
  symbol: string;
2202
- currentPrice: number;
2203
- historicalPrice: number | null;
2204
- change: number | null;
2205
- period: "1h" | "24h" | "7d" | "30d";
2206
- }>;
2207
- declare const defillamaChainTvlTool: Tool<{
2208
- limit?: number | undefined;
2209
- }, {
2210
- rank: number;
2211
- chain: string;
2212
- tvl: number;
2213
- }[]>;
2214
- declare const defillamaProtocolFeesTool: Tool<{
2215
- limit?: number | undefined;
2216
- chain?: string | undefined;
2217
- }, {
2218
- name: string;
2219
- fees24h: number | null;
2220
- fees7d: number | null;
2221
- category: string | undefined;
2222
- }[]>;
2223
- declare const defillamaSuiProtocolsTool: Tool<{
2224
- limit?: number | undefined;
2225
- }, {
2226
- name: string;
2227
- slug: string;
2228
- tvl: number;
2229
- category: string;
2230
- }[]>;
2291
+ price: null;
2292
+ priceUnavailable: boolean;
2293
+ })[]>;
2231
2294
 
2232
2295
  declare const READ_TOOLS: Tool[];
2233
2296
  declare const WRITE_TOOLS: Tool[];
@@ -2292,19 +2355,6 @@ interface WalletCoin {
2292
2355
  */
2293
2356
  declare function fetchWalletCoins(address: string, rpcUrl?: string): Promise<WalletCoin[]>;
2294
2357
 
2295
- /**
2296
- * Batch-fetch USD prices for Sui coin types from DefiLlama.
2297
- * Returns a map of `coinType -> usdPrice`. Tokens not found return no entry.
2298
- *
2299
- * Cache behavior (post-0.47): merge-on-miss. If the cache is valid but missing
2300
- * a few requested coin types, we fetch ONLY the missing ones and merge them
2301
- * into the cached map — instead of throwing the entire cache away. This is
2302
- * the common path when a wallet adds one new memecoin to a portfolio that
2303
- * already has USDC/SUI prices cached. Saves ~0.5–1.5s on warm calls.
2304
- */
2305
- declare function fetchTokenPrices(coinTypes: string[]): Promise<Record<string, number>>;
2306
- declare function clearPriceCache(): void;
2307
-
2308
- 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 40 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- 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- \"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.";
2358
+ 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- 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 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 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\": 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 is USDC only.\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.";
2309
2359
 
2310
- export { AnthropicProvider, type AnthropicProviderConfig, 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, 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 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, clearPriceCache, compactMessages, createGuardRunnerState, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, 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, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
2360
+ export { type AddressPortfolio, AnthropicProvider, type AnthropicProviderConfig, 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, 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, fetchAddressPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, 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 };