@t2000/engine 0.33.2 → 0.35.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
@@ -152,6 +152,12 @@ declare class TxMutex {
152
152
  release(): void;
153
153
  }
154
154
  declare function runTools(pending: PendingToolCall[], tools: Tool[], context: ToolContext, txMutex: TxMutex): AsyncGenerator<EngineEvent>;
155
+ /**
156
+ * Enforce per-tool result size limits. When a serialized result exceeds
157
+ * `maxResultSizeChars`, truncate it with a hint to re-call with narrower
158
+ * parameters. Uses the tool's custom `summarizeOnTruncate` when available.
159
+ */
160
+ declare function budgetToolResult(data: unknown, tool: Tool): unknown;
155
161
 
156
162
  type GuardVerdict = 'pass' | 'hint' | 'warn' | 'block';
157
163
  type GuardTier = 'safety' | 'financial' | 'ux';
@@ -240,6 +246,106 @@ declare function extractConversationText(messages: Array<{
240
246
  lastAssistantText: string;
241
247
  };
242
248
 
249
+ /**
250
+ * USD-aware permission resolution for write tools.
251
+ *
252
+ * Replaces the binary auto/confirm/explicit system with dollar-threshold
253
+ * tiers that resolve at runtime based on the transaction value and
254
+ * per-user configuration.
255
+ */
256
+ type PermissionOperation = 'save' | 'withdraw' | 'send' | 'borrow' | 'repay' | 'swap' | 'pay';
257
+ interface PermissionRule {
258
+ operation: PermissionOperation;
259
+ /** Auto-execute if USD amount is below this threshold. */
260
+ autoBelow: number;
261
+ /** Confirm if between autoBelow and this. Explicit for anything above. */
262
+ confirmBetween: number;
263
+ }
264
+ interface UserPermissionConfig {
265
+ rules: PermissionRule[];
266
+ /** Fallback auto threshold for operations without a specific rule. */
267
+ globalAutoBelow: number;
268
+ /** Max total USD of autonomous actions per day (safety net). */
269
+ autonomousDailyLimit: number;
270
+ }
271
+ declare const DEFAULT_PERMISSION_CONFIG: UserPermissionConfig;
272
+ declare const PERMISSION_PRESETS: {
273
+ conservative: {
274
+ globalAutoBelow: number;
275
+ autonomousDailyLimit: number;
276
+ rules: ({
277
+ operation: "save";
278
+ autoBelow: number;
279
+ confirmBetween: number;
280
+ } | {
281
+ operation: "send";
282
+ autoBelow: number;
283
+ confirmBetween: number;
284
+ } | {
285
+ operation: "borrow";
286
+ autoBelow: number;
287
+ confirmBetween: number;
288
+ } | {
289
+ operation: "withdraw";
290
+ autoBelow: number;
291
+ confirmBetween: number;
292
+ } | {
293
+ operation: "swap";
294
+ autoBelow: number;
295
+ confirmBetween: number;
296
+ } | {
297
+ operation: "pay";
298
+ autoBelow: number;
299
+ confirmBetween: number;
300
+ } | {
301
+ operation: "repay";
302
+ autoBelow: number;
303
+ confirmBetween: number;
304
+ })[];
305
+ };
306
+ balanced: UserPermissionConfig;
307
+ aggressive: {
308
+ globalAutoBelow: number;
309
+ autonomousDailyLimit: number;
310
+ rules: ({
311
+ operation: "save";
312
+ autoBelow: number;
313
+ confirmBetween: number;
314
+ } | {
315
+ operation: "send";
316
+ autoBelow: number;
317
+ confirmBetween: number;
318
+ } | {
319
+ operation: "borrow";
320
+ autoBelow: number;
321
+ confirmBetween: number;
322
+ } | {
323
+ operation: "withdraw";
324
+ autoBelow: number;
325
+ confirmBetween: number;
326
+ } | {
327
+ operation: "swap";
328
+ autoBelow: number;
329
+ confirmBetween: number;
330
+ } | {
331
+ operation: "pay";
332
+ autoBelow: number;
333
+ confirmBetween: number;
334
+ } | {
335
+ operation: "repay";
336
+ autoBelow: number;
337
+ confirmBetween: number;
338
+ })[];
339
+ };
340
+ };
341
+ declare function resolvePermissionTier(operation: string, amountUsd: number, config: UserPermissionConfig): 'auto' | 'confirm' | 'explicit';
342
+ declare function toolNameToOperation(toolName: string): PermissionOperation | undefined;
343
+ /**
344
+ * Resolve the USD value of a tool call from its inputs.
345
+ * USDC-denominated tools return 1:1. Others multiply by the price cache.
346
+ */
347
+ declare function resolveUsdValue(toolName: string, input: Record<string, unknown>, priceCache: Map<string, number>): number;
348
+
243
349
  type ContentBlock = {
244
350
  type: 'text';
245
351
  text: string;
@@ -358,6 +464,10 @@ interface ToolContext {
358
464
  /** Environment variables passed to tools (e.g. API keys not in process.env) */
359
465
  env?: Record<string, string>;
360
466
  signal?: AbortSignal;
467
+ /** Token symbol → USD price map for USD-aware permission resolution (B.4). */
468
+ priceCache?: Map<string, number>;
469
+ /** Per-user permission config for USD-threshold write tool gating (B.4). */
470
+ permissionConfig?: UserPermissionConfig;
361
471
  }
362
472
  interface ServerPositionData {
363
473
  savings: number;
@@ -412,6 +522,10 @@ interface Tool<TInput = unknown, TOutput = unknown> {
412
522
  permissionLevel: PermissionLevel;
413
523
  flags: ToolFlags;
414
524
  preflight?: (input: unknown) => PreflightResult;
525
+ /** Max chars for the serialized tool result. Truncated with a re-call hint when exceeded. */
526
+ maxResultSizeChars?: number;
527
+ /** Custom truncation strategy. Falls back to generic slice + hint when omitted. */
528
+ summarizeOnTruncate?: (result: string, maxChars: number) => string;
415
529
  }
416
530
  type ThinkingEffort = 'low' | 'medium' | 'high' | 'max';
417
531
  type ThinkingConfig = {
@@ -469,6 +583,10 @@ interface EngineConfig {
469
583
  contextBudget?: ContextBudgetConfig;
470
584
  /** LLM-based summarizer for context compaction (RE-3.3). */
471
585
  contextSummarizer?: (messages: Message[]) => Promise<string>;
586
+ /** Token symbol → USD price map for USD-aware permission resolution (B.4). */
587
+ priceCache?: Map<string, number>;
588
+ /** Per-user permission config for USD-threshold write tool gating (B.4). */
589
+ permissionConfig?: UserPermissionConfig;
472
590
  }
473
591
  interface LLMProvider {
474
592
  chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
@@ -589,6 +707,8 @@ declare class QueryEngine {
589
707
  private readonly recipes;
590
708
  private readonly contextBudget;
591
709
  private readonly contextSummarizer;
710
+ private readonly priceCache;
711
+ private readonly permissionConfig;
592
712
  private matchedRecipe;
593
713
  private messages;
594
714
  private abortController;
@@ -650,6 +770,8 @@ interface BuildToolOptions<TInput, TOutput> {
650
770
  permissionLevel?: PermissionLevel;
651
771
  flags?: ToolFlags;
652
772
  preflight?: (input: TInput) => PreflightResult;
773
+ maxResultSizeChars?: number;
774
+ summarizeOnTruncate?: (result: string, maxChars: number) => string;
653
775
  }
654
776
  declare function buildTool<TInput, TOutput>(opts: BuildToolOptions<TInput, TOutput>): Tool<TInput, TOutput>;
655
777
  declare function toolsToDefinitions(tools: Tool[]): {
@@ -861,6 +983,52 @@ interface ConversationStateStore {
861
983
  }
862
984
  declare function buildStateContext(state: ConversationState): string;
863
985
 
986
+ /**
987
+ * Zero-cost deduplication pass: if the same tool was called with identical
988
+ * inputs earlier in the conversation and the result hasn't changed, replace
989
+ * the full prior result with a compact back-reference. Runs before any
990
+ * LLM-based compaction and costs nothing.
991
+ *
992
+ * Returns a new array — does not mutate the input.
993
+ */
994
+ declare function microcompact(messages: readonly Message[]): Message[];
995
+
996
+ /**
997
+ * EarlyToolDispatcher — dispatches read-only tools mid-stream.
998
+ *
999
+ * When the LLM emits `tool_use_done` for a read-only tool, the dispatcher
1000
+ * fires it immediately in the background rather than waiting for the full
1001
+ * stream to finish. Results are collected in original call order after the
1002
+ * stream exits.
1003
+ *
1004
+ * Write tools are NOT dispatched — they go through the existing permission
1005
+ * gate and TxMutex flow.
1006
+ */
1007
+
1008
+ declare class EarlyToolDispatcher {
1009
+ private entries;
1010
+ private readonly tools;
1011
+ private readonly context;
1012
+ private abortController;
1013
+ constructor(tools: Tool[], context: ToolContext);
1014
+ /**
1015
+ * Attempt to dispatch a tool call. Returns true if the tool was dispatched
1016
+ * (read-only + concurrency-safe), false if it should be queued for later.
1017
+ */
1018
+ tryDispatch(call: PendingToolCall): boolean;
1019
+ /** True if any tools have been dispatched. */
1020
+ hasPending(): boolean;
1021
+ /** List of call IDs that were early-dispatched. */
1022
+ dispatchedIds(): Set<string>;
1023
+ /**
1024
+ * Collect all results in original dispatch order.
1025
+ * Yields `tool_result` events as each promise resolves.
1026
+ */
1027
+ collectResults(): AsyncGenerator<EngineEvent>;
1028
+ /** Cancel all in-flight tool calls. */
1029
+ abort(): void;
1030
+ }
1031
+
864
1032
  interface McpToolDescriptor {
865
1033
  name: string;
866
1034
  description: string;
@@ -1666,4 +1834,4 @@ declare function clearPriceCache(): void;
1666
1834
 
1667
1835
  declare const DEFAULT_SYSTEM_PROMPT = "You are a financial agent on Sui. You manage money and access paid APIs via MPP micropayments.\n\n## Response rules\n- 1-2 sentences max. No bullet lists unless asked. No preambles.\n- Never say \"Would you like me to...\", \"Sure!\", \"Great question!\", \"Absolutely!\" \u2014 just do it or say you can't.\n- Lead with the result. After tool calls, state the outcome with real numbers. Done.\n- Present amounts as $1,234.56 and rates as X.XX% APY.\n- Show top 3 results unless asked for more. Summarize totals in one line.\n\n## Execution rule\nOnly offer to execute actions you have tools for. If you retrieved a quote, data, or information but have no tool to act on it, give the user the result and tell them where to execute manually \u2014 in one sentence. Never say \"Would you like me to proceed?\" unless you have a tool that can actually proceed.\n\n## Before acting\n- ALWAYS call a read tool first before any write tool \u2014 balance_check before save/send/borrow, savings_info before withdraw.\n- Show real numbers from tools \u2014 never fabricate rates, amounts, or balances.\n- When user says \"all\" or an imprecise amount, call the read tool first to get the exact number.\n\n## Tool usage\n- Use tools proactively \u2014 don't refuse requests you can handle.\n- For real-world questions (weather, search, news, prices), use pay_api. Tell the user the cost first.\n- For broad market data (yields across protocols, token prices, TVL, protocol comparisons), use defillama_* tools.\n- To discover Sui protocols, use defillama_sui_protocols first, then defillama_protocol_info with the slug.\n- Run multiple read-only tools in parallel when you need several data points.\n- If a tool errors, say what went wrong and what to try instead. One sentence.\n\n## Savings = USDC only (critical)\n- save_deposit accepts ONLY USDC. No other token can be deposited into savings.\n- When asked \"how much can I save?\", report only the user's USDC wallet balance (saveableUsdc field from balance_check). Other tokens like GOLD, SUI, USDT are NOT saveable and NOT savings positions \u2014 they are just wallet holdings.\n- NEVER say a non-USDC token is \"in savings\" or \"earning APY in savings\" unless it appears in the savings_info positions list. Wallet holdings \u2260 savings.\n- If user wants to save non-USDC tokens, tell them to swap to USDC first. Do NOT auto-chain swap + deposit.\n\n## Multi-step flows\n- \"How much X for Y?\": swap_quote first, then swap_execute if user confirms.\n- \"Swap then save\": swap_execute \u2192 balance_check \u2192 save_deposit. Confirm each step.\n- \"Buy $X of token\": defillama_token_prices \u2192 calculate amount \u2192 swap_execute.\n- \"Best yield on SUI\": compare rates_info (NAVI lending) + defillama_yield_pools (broader) + volo_stats.\n- withdraw supports legacy positions: USDC, USDe, USDsui, SUI. Pass asset param to withdraw a specific token.\n- \"Deposit SUI to earn yield\": volo_stake for SUI liquid staking. save_deposit is USDC only.\n- \"What protocols are on Sui?\": defillama_sui_protocols \u2192 defillama_protocol_info for details.\n\n## Safety\n- Never encourage risky financial behavior.\n- Warn when health factor < 1.5.\n- All amounts in USDC unless stated otherwise.";
1668
1836
 
1669
- 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_SYSTEM_PROMPT, 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, type PendingAction, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionResponse, 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, type ThinkingConfig, type ThinkingEffort, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolFlags, type ToolJsonSchema, type ToolResult, TxMutex, type UserFinancialProfile, WRITE_TOOLS, type WalletCoin, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, balanceCheckTool, borrowTool, 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, getToolFlags, getWalletAddress, guardArtifactPreview, guardStaleData, hasNaviMcp, healthCheckTool, loadRecipes, mppServicesTool, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
1837
+ 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 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, 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, 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 };