@t2000/engine 0.51.1 → 0.52.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 +60 -2
- package/dist/index.js +132 -10
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -2022,8 +2022,8 @@ declare const transactionHistoryTool: Tool<{
|
|
|
2022
2022
|
action?: "send" | "swap" | "transaction" | "lending" | undefined;
|
|
2023
2023
|
date?: string | undefined;
|
|
2024
2024
|
address?: string | undefined;
|
|
2025
|
-
direction?: "out" | "in" | undefined;
|
|
2026
2025
|
limit?: number | undefined;
|
|
2026
|
+
direction?: "out" | "in" | undefined;
|
|
2027
2027
|
counterparty?: string | undefined;
|
|
2028
2028
|
minUsd?: number | undefined;
|
|
2029
2029
|
assetSymbol?: string | undefined;
|
|
@@ -2394,6 +2394,64 @@ interface WalletCoin {
|
|
|
2394
2394
|
*/
|
|
2395
2395
|
declare function fetchWalletCoins(address: string, rpcUrl?: string): Promise<WalletCoin[]>;
|
|
2396
2396
|
|
|
2397
|
+
/**
|
|
2398
|
+
* Resolve the audric API base URL from the engine's env shim, falling
|
|
2399
|
+
* back to `process.env`. Returns `null` when no override is configured —
|
|
2400
|
+
* callers MUST treat this as "use in-engine fallback path".
|
|
2401
|
+
*
|
|
2402
|
+
* Lookup order (first defined wins):
|
|
2403
|
+
* 1. `env.T2000_AUDRIC_API` — canonical override
|
|
2404
|
+
* 2. `process.env.T2000_AUDRIC_API` — same, picked up directly
|
|
2405
|
+
* 3. `env.AUDRIC_INTERNAL_API_URL` — legacy alias from audric host
|
|
2406
|
+
* 4. `process.env.AUDRIC_INTERNAL_API_URL`
|
|
2407
|
+
* 5. `process.env.NEXT_PUBLIC_APP_URL` — last-ditch host hint
|
|
2408
|
+
*/
|
|
2409
|
+
declare function getAudricApiBase(env?: Record<string, string>): string | null;
|
|
2410
|
+
interface AudricPortfolioResult {
|
|
2411
|
+
/** Wallet half — directly compatible with the existing `AddressPortfolio` shape. */
|
|
2412
|
+
portfolio: AddressPortfolio;
|
|
2413
|
+
/** NAVI lending positions, normalized to the engine's `ServerPositionData`. */
|
|
2414
|
+
positions: ServerPositionData;
|
|
2415
|
+
/** Net worth derived audric-side (`wallet + savings - borrows`). */
|
|
2416
|
+
netWorthUsd: number;
|
|
2417
|
+
/** `savings * savingsRate / 365`, capped at 0. */
|
|
2418
|
+
estimatedDailyYield: number;
|
|
2419
|
+
/** Per-symbol balance map — convenient for adapters that already used `WalletBalances`. */
|
|
2420
|
+
walletAllocations: Record<string, number>;
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* Fetch the canonical portfolio snapshot from audric. Returns `null` if
|
|
2424
|
+
* audric isn't configured for this runtime, or if the request fails for
|
|
2425
|
+
* any reason — callers MUST fall back to the in-engine BlockVision +
|
|
2426
|
+
* NAVI path on `null`.
|
|
2427
|
+
*/
|
|
2428
|
+
declare function fetchAudricPortfolio(address: string, env?: Record<string, string>, signal?: AbortSignal): Promise<AudricPortfolioResult | null>;
|
|
2429
|
+
interface AudricHistoryRecord {
|
|
2430
|
+
digest: string;
|
|
2431
|
+
action: string;
|
|
2432
|
+
label?: string;
|
|
2433
|
+
direction?: 'in' | 'out';
|
|
2434
|
+
amount?: number;
|
|
2435
|
+
asset?: string;
|
|
2436
|
+
/** Counterparty address (only set for transfers with a clear recipient). */
|
|
2437
|
+
recipient?: string;
|
|
2438
|
+
timestamp: number;
|
|
2439
|
+
date?: string;
|
|
2440
|
+
gasCost?: number;
|
|
2441
|
+
}
|
|
2442
|
+
/**
|
|
2443
|
+
* Fetch the canonical transaction history list from audric. Same fall
|
|
2444
|
+
* back contract as `fetchAudricPortfolio` — `null` means "use in-engine
|
|
2445
|
+
* Sui-RPC path". Audric's `/api/history` already merges `FromAddress` +
|
|
2446
|
+
* `ToAddress`, dedupes by digest, and parses Move calls via
|
|
2447
|
+
* `@t2000/sdk`'s shared parser, so the wire shape is a 1:1 match for the
|
|
2448
|
+
* engine's existing `TxRecord` once we rename `counterparty` →
|
|
2449
|
+
* `recipient`.
|
|
2450
|
+
*/
|
|
2451
|
+
declare function fetchAudricHistory(address: string, opts: {
|
|
2452
|
+
limit?: number;
|
|
2453
|
+
}, env?: Record<string, string>, signal?: AbortSignal): Promise<AudricHistoryRecord[] | null>;
|
|
2454
|
+
|
|
2397
2455
|
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 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.";
|
|
2398
2456
|
|
|
2399
|
-
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 };
|
|
2457
|
+
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, 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, 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 };
|
package/dist/index.js
CHANGED
|
@@ -1101,6 +1101,92 @@ function clearPriceMapCache() {
|
|
|
1101
1101
|
priceMapCache = null;
|
|
1102
1102
|
}
|
|
1103
1103
|
|
|
1104
|
+
// src/audric-api.ts
|
|
1105
|
+
var FETCH_TIMEOUT_MS = 6e3;
|
|
1106
|
+
function getAudricApiBase(env) {
|
|
1107
|
+
const fromEnv = env?.T2000_AUDRIC_API ?? env?.AUDRIC_INTERNAL_API_URL ?? null;
|
|
1108
|
+
if (fromEnv && fromEnv.trim().length > 0) return fromEnv.replace(/\/$/, "");
|
|
1109
|
+
const fromProcess = process.env.T2000_AUDRIC_API ?? process.env.AUDRIC_INTERNAL_API_URL ?? process.env.NEXT_PUBLIC_APP_URL ?? null;
|
|
1110
|
+
if (fromProcess && fromProcess.trim().length > 0) return fromProcess.replace(/\/$/, "");
|
|
1111
|
+
return null;
|
|
1112
|
+
}
|
|
1113
|
+
async function fetchAudricPortfolio(address, env, signal) {
|
|
1114
|
+
const base = getAudricApiBase(env);
|
|
1115
|
+
if (!base) return null;
|
|
1116
|
+
try {
|
|
1117
|
+
const res = await fetch(
|
|
1118
|
+
`${base}/api/portfolio?address=${encodeURIComponent(address)}`,
|
|
1119
|
+
{ signal: signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS) }
|
|
1120
|
+
);
|
|
1121
|
+
if (!res.ok) {
|
|
1122
|
+
console.warn(`[audric-api] portfolio ${address.slice(0, 10)} \u2192 HTTP ${res.status}`);
|
|
1123
|
+
return null;
|
|
1124
|
+
}
|
|
1125
|
+
const json = await res.json();
|
|
1126
|
+
const portfolio = {
|
|
1127
|
+
coins: Array.isArray(json.wallet) ? json.wallet : [],
|
|
1128
|
+
totalUsd: json.walletValueUsd ?? 0,
|
|
1129
|
+
pricedAt: json.pricedAt ?? Date.now(),
|
|
1130
|
+
source: json.source ?? "blockvision"
|
|
1131
|
+
};
|
|
1132
|
+
const positions = {
|
|
1133
|
+
savings: json.positions?.savings ?? 0,
|
|
1134
|
+
borrows: json.positions?.borrows ?? 0,
|
|
1135
|
+
savingsRate: json.positions?.savingsRate ?? 0,
|
|
1136
|
+
healthFactor: json.positions?.healthFactor ?? null,
|
|
1137
|
+
maxBorrow: json.positions?.maxBorrow ?? 0,
|
|
1138
|
+
pendingRewards: json.positions?.pendingRewards ?? 0,
|
|
1139
|
+
supplies: json.positions?.supplies ?? [],
|
|
1140
|
+
// The engine type calls this `borrows_detail`; audric's wire shape
|
|
1141
|
+
// calls it `borrowsDetail`. Normalize on the engine side so
|
|
1142
|
+
// downstream tools can keep their existing field names.
|
|
1143
|
+
borrows_detail: json.positions?.borrowsDetail ?? []
|
|
1144
|
+
};
|
|
1145
|
+
return {
|
|
1146
|
+
portfolio,
|
|
1147
|
+
positions,
|
|
1148
|
+
netWorthUsd: json.netWorthUsd ?? portfolio.totalUsd + positions.savings - positions.borrows,
|
|
1149
|
+
estimatedDailyYield: json.estimatedDailyYield ?? 0,
|
|
1150
|
+
walletAllocations: json.walletAllocations ?? {}
|
|
1151
|
+
};
|
|
1152
|
+
} catch (err) {
|
|
1153
|
+
console.warn(`[audric-api] portfolio ${address.slice(0, 10)} fetch failed:`, err);
|
|
1154
|
+
return null;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
async function fetchAudricHistory(address, opts, env, signal) {
|
|
1158
|
+
const base = getAudricApiBase(env);
|
|
1159
|
+
if (!base) return null;
|
|
1160
|
+
const params = new URLSearchParams({ address });
|
|
1161
|
+
if (opts.limit != null) params.set("limit", String(opts.limit));
|
|
1162
|
+
try {
|
|
1163
|
+
const res = await fetch(`${base}/api/history?${params}`, {
|
|
1164
|
+
signal: signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
1165
|
+
});
|
|
1166
|
+
if (!res.ok) {
|
|
1167
|
+
console.warn(`[audric-api] history ${address.slice(0, 10)} \u2192 HTTP ${res.status}`);
|
|
1168
|
+
return null;
|
|
1169
|
+
}
|
|
1170
|
+
const json = await res.json();
|
|
1171
|
+
const items = Array.isArray(json.items) ? json.items : [];
|
|
1172
|
+
return items.map((item) => ({
|
|
1173
|
+
digest: item.digest,
|
|
1174
|
+
action: item.action,
|
|
1175
|
+
label: item.label,
|
|
1176
|
+
direction: item.direction,
|
|
1177
|
+
amount: item.amount,
|
|
1178
|
+
asset: item.asset,
|
|
1179
|
+
recipient: item.counterparty,
|
|
1180
|
+
timestamp: item.timestamp,
|
|
1181
|
+
date: item.timestamp > 0 ? new Date(item.timestamp).toISOString() : void 0,
|
|
1182
|
+
gasCost: item.gasCost
|
|
1183
|
+
}));
|
|
1184
|
+
} catch (err) {
|
|
1185
|
+
console.warn(`[audric-api] history ${address.slice(0, 10)} fetch failed:`, err);
|
|
1186
|
+
return null;
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1104
1190
|
// src/tools/balance.ts
|
|
1105
1191
|
var GAS_RESERVE_SUI2 = 0.05;
|
|
1106
1192
|
var SUI_ADDRESS_REGEX = /^0x[a-fA-F0-9]{1,64}$/;
|
|
@@ -1186,8 +1272,15 @@ var balanceCheckTool = buildTool({
|
|
|
1186
1272
|
const address = targetAddress;
|
|
1187
1273
|
const mgr = getMcpManager(context);
|
|
1188
1274
|
const hasPositionFetcher = !!context.positionFetcher;
|
|
1275
|
+
const audricPortfolio = await fetchAudricPortfolio(
|
|
1276
|
+
address,
|
|
1277
|
+
context.env,
|
|
1278
|
+
context.signal
|
|
1279
|
+
);
|
|
1280
|
+
const usingAudricSnapshot = audricPortfolio !== null;
|
|
1281
|
+
const audric = audricPortfolio;
|
|
1189
1282
|
const [portfolio, positions, rewards, serverPositions, defiPortfolio] = await Promise.all([
|
|
1190
|
-
loadPortfolio(
|
|
1283
|
+
usingAudricSnapshot ? Promise.resolve(audric.portfolio) : loadPortfolio(
|
|
1191
1284
|
address,
|
|
1192
1285
|
context.blockvisionApiKey,
|
|
1193
1286
|
context.suiRpcUrl,
|
|
@@ -1202,7 +1295,7 @@ var balanceCheckTool = buildTool({
|
|
|
1202
1295
|
};
|
|
1203
1296
|
return fallback;
|
|
1204
1297
|
}),
|
|
1205
|
-
hasPositionFetcher ? Promise.resolve(null) : callNavi(mgr, NaviTools.GET_POSITIONS, {
|
|
1298
|
+
usingAudricSnapshot || hasPositionFetcher ? Promise.resolve(null) : callNavi(mgr, NaviTools.GET_POSITIONS, {
|
|
1206
1299
|
address,
|
|
1207
1300
|
protocols: "navi",
|
|
1208
1301
|
format: "json"
|
|
@@ -1210,11 +1303,11 @@ var balanceCheckTool = buildTool({
|
|
|
1210
1303
|
console.warn("[balance_check] NAVI GET_POSITIONS failed:", err);
|
|
1211
1304
|
return null;
|
|
1212
1305
|
}),
|
|
1213
|
-
hasPositionFetcher ? Promise.resolve(null) : callNavi(mgr, NaviTools.GET_AVAILABLE_REWARDS, { address }).catch((err) => {
|
|
1306
|
+
usingAudricSnapshot || hasPositionFetcher ? Promise.resolve(null) : callNavi(mgr, NaviTools.GET_AVAILABLE_REWARDS, { address }).catch((err) => {
|
|
1214
1307
|
console.warn("[balance_check] NAVI GET_AVAILABLE_REWARDS failed:", err);
|
|
1215
1308
|
return null;
|
|
1216
1309
|
}),
|
|
1217
|
-
hasPositionFetcher ? context.positionFetcher(address).catch((err) => {
|
|
1310
|
+
usingAudricSnapshot ? Promise.resolve(audric.positions) : hasPositionFetcher ? context.positionFetcher(address).catch((err) => {
|
|
1218
1311
|
console.warn("[balance_check] positionFetcher failed:", err);
|
|
1219
1312
|
return null;
|
|
1220
1313
|
}) : Promise.resolve(null),
|
|
@@ -2051,9 +2144,34 @@ var transactionHistoryTool = buildTool({
|
|
|
2051
2144
|
displayText: `${filtered2.length} recent transaction(s)`
|
|
2052
2145
|
};
|
|
2053
2146
|
}
|
|
2054
|
-
if (!targetAddress
|
|
2147
|
+
if (!targetAddress) {
|
|
2055
2148
|
throw new Error("Transaction history requires a wallet address");
|
|
2056
2149
|
}
|
|
2150
|
+
if (!input.date) {
|
|
2151
|
+
const audricRecords = await fetchAudricHistory(
|
|
2152
|
+
targetAddress,
|
|
2153
|
+
{ limit: Math.max(limit * 4, 50) },
|
|
2154
|
+
context.env,
|
|
2155
|
+
context.signal
|
|
2156
|
+
);
|
|
2157
|
+
if (audricRecords) {
|
|
2158
|
+
const cutoffMs2 = Date.now() - DEFAULT_LOOKBACK_DAYS * 864e5;
|
|
2159
|
+
const recent2 = audricRecords.filter((r) => r.timestamp >= cutoffMs2);
|
|
2160
|
+
const filtered2 = finalize(recent2);
|
|
2161
|
+
return {
|
|
2162
|
+
data: {
|
|
2163
|
+
transactions: filtered2,
|
|
2164
|
+
count: filtered2.length,
|
|
2165
|
+
...filterMeta,
|
|
2166
|
+
lookbackDays: DEFAULT_LOOKBACK_DAYS
|
|
2167
|
+
},
|
|
2168
|
+
displayText: `${filtered2.length} transaction(s) in the last ${DEFAULT_LOOKBACK_DAYS} days`
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
if (!context.suiRpcUrl) {
|
|
2173
|
+
throw new Error("Transaction history requires a Sui RPC URL when audric API is unavailable");
|
|
2174
|
+
}
|
|
2057
2175
|
if (input.date) {
|
|
2058
2176
|
const records2 = await queryHistoryByDate(
|
|
2059
2177
|
context.suiRpcUrl,
|
|
@@ -3019,9 +3137,14 @@ var portfolioAnalysisTool = buildTool({
|
|
|
3019
3137
|
throw new Error("No wallet address provided. Sign in first.");
|
|
3020
3138
|
}
|
|
3021
3139
|
const DUST_USD = 0.01;
|
|
3140
|
+
const audricSnapshot = await fetchAudricPortfolio(
|
|
3141
|
+
address,
|
|
3142
|
+
context.env,
|
|
3143
|
+
context.signal
|
|
3144
|
+
);
|
|
3022
3145
|
const apiUrl = context.env?.AUDRIC_INTERNAL_API_URL;
|
|
3023
3146
|
const [portfolio, positions, weekHistResult] = await Promise.all([
|
|
3024
|
-
(async () => {
|
|
3147
|
+
audricSnapshot ? Promise.resolve(audricSnapshot.portfolio) : (async () => {
|
|
3025
3148
|
if (context.portfolioCache) {
|
|
3026
3149
|
const hit = context.portfolioCache.get(address);
|
|
3027
3150
|
if (hit) return hit;
|
|
@@ -3035,15 +3158,14 @@ var portfolioAnalysisTool = buildTool({
|
|
|
3035
3158
|
return fresh;
|
|
3036
3159
|
})().catch((err) => {
|
|
3037
3160
|
console.warn("[portfolio_analysis] portfolio fetch failed:", err);
|
|
3038
|
-
|
|
3161
|
+
return {
|
|
3039
3162
|
coins: [],
|
|
3040
3163
|
totalUsd: 0,
|
|
3041
3164
|
pricedAt: Date.now(),
|
|
3042
3165
|
source: "sui-rpc-degraded"
|
|
3043
3166
|
};
|
|
3044
|
-
return empty;
|
|
3045
3167
|
}),
|
|
3046
|
-
context.positionFetcher ? context.positionFetcher(address).catch((err) => {
|
|
3168
|
+
audricSnapshot ? Promise.resolve(audricSnapshot.positions) : context.positionFetcher ? context.positionFetcher(address).catch((err) => {
|
|
3047
3169
|
console.warn("[portfolio_analysis] positionFetcher failed:", err);
|
|
3048
3170
|
return null;
|
|
3049
3171
|
}) : Promise.resolve(null),
|
|
@@ -7363,6 +7485,6 @@ function sanitizeAnthropicMessages(messages) {
|
|
|
7363
7485
|
return merged;
|
|
7364
7486
|
}
|
|
7365
7487
|
|
|
7366
|
-
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, 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 };
|
|
7488
|
+
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, 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 };
|
|
7367
7489
|
//# sourceMappingURL=index.js.map
|
|
7368
7490
|
//# sourceMappingURL=index.js.map
|