@t2000/engine 0.32.0 → 0.33.1

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
@@ -5,6 +5,141 @@ import { Tool as Tool$1 } from '@modelcontextprotocol/sdk/types.js';
5
5
  import * as _t2000_sdk from '@t2000/sdk';
6
6
  import { T2000 } from '@t2000/sdk';
7
7
 
8
+ /** Rough token count for a message array. */
9
+ declare function estimateTokens(messages: Message[]): number;
10
+ interface CompactOptions {
11
+ /** Max token budget for the conversation. Default 100_000. */
12
+ maxTokens?: number;
13
+ /** Number of recent messages to always keep uncompacted. Default 8. */
14
+ keepRecentCount?: number;
15
+ /** System prompt token estimate (subtracted from budget). Default 500. */
16
+ systemPromptTokens?: number;
17
+ /** LLM-based summarizer for old turns. When provided, replaces old turns with a summary. */
18
+ summarizer?: (messages: Message[]) => Promise<string>;
19
+ }
20
+ interface ContextBudgetConfig {
21
+ /** Total context window size in tokens. Default 200_000 (Sonnet 4.6). */
22
+ contextLimit?: number;
23
+ /** Trigger compaction at this fraction of contextLimit. Default 0.85. */
24
+ compactThreshold?: number;
25
+ /** Emit a warning at this fraction of contextLimit. Default 0.70. */
26
+ warnThreshold?: number;
27
+ }
28
+ declare class ContextBudget {
29
+ private estimatedTokens;
30
+ private readonly contextLimit;
31
+ private readonly compactThreshold;
32
+ private readonly warnThreshold;
33
+ constructor(config?: ContextBudgetConfig);
34
+ /** Update with actual input_tokens from the API usage event. */
35
+ update(inputTokens: number): void;
36
+ /** True when the session should be compacted (at 85% of context limit). */
37
+ shouldCompact(): boolean;
38
+ /** True when nearing the limit (at 70% of context limit). */
39
+ shouldWarn(): boolean;
40
+ /** Current token count. */
41
+ get tokens(): number;
42
+ /** Remaining tokens before compaction triggers. */
43
+ get remaining(): number;
44
+ /** Usage ratio (0..1). */
45
+ get usage(): number;
46
+ reset(): void;
47
+ }
48
+ /**
49
+ * Compact a conversation that exceeds the token budget.
50
+ *
51
+ * Strategy:
52
+ * 1. Always preserve the most recent `keepRecentCount` messages (the active context).
53
+ * 2. If an LLM `summarizer` is provided, summarize old turns into a brief recap and
54
+ * replace them with a synthetic summary turn pair.
55
+ * 3. For older messages, summarise tool_result content to a brief one-liner.
56
+ * 4. If still over budget, drop the oldest messages (keeping the first user message
57
+ * for context continuity).
58
+ *
59
+ * Returns a new array — does not mutate the input.
60
+ */
61
+ declare function compactMessages(messages: readonly Message[], opts?: CompactOptions): Promise<Message[]>;
62
+
63
+ interface RecipeStepRequirement {
64
+ step?: string;
65
+ field?: string;
66
+ confirmation?: boolean;
67
+ }
68
+ interface RecipeStepOnError {
69
+ action: 'abort' | 'refuse' | 'report' | 'retry';
70
+ message: string;
71
+ suggest?: string;
72
+ }
73
+ interface RecipePrerequisite {
74
+ field: string;
75
+ prompt: string;
76
+ }
77
+ interface RecipeStep {
78
+ name: string;
79
+ tool?: string;
80
+ service?: string;
81
+ purpose: string;
82
+ cost?: string;
83
+ output?: {
84
+ type: string;
85
+ key: string;
86
+ };
87
+ gate?: 'none' | 'preview' | 'review' | 'estimate';
88
+ gate_prompt?: string;
89
+ requires?: RecipeStepRequirement[];
90
+ rules?: string[];
91
+ condition?: string;
92
+ notes?: string;
93
+ flags?: Partial<ToolFlags>;
94
+ on_error?: RecipeStepOnError;
95
+ input_template?: Record<string, string>;
96
+ cost_per_unit?: string;
97
+ }
98
+ interface Recipe {
99
+ name: string;
100
+ description: string;
101
+ triggers: string[];
102
+ services?: string[];
103
+ prerequisites?: RecipePrerequisite[];
104
+ steps: RecipeStep[];
105
+ }
106
+
107
+ /**
108
+ * Stores loaded recipes and matches user messages to the most specific recipe
109
+ * using longest-trigger-match-wins.
110
+ */
111
+ declare class RecipeRegistry {
112
+ private recipes;
113
+ /** Load all recipes from a directory of YAML files. */
114
+ loadDir(yamlDir: string): void;
115
+ /** Register a single recipe from a YAML string. */
116
+ loadYaml(yamlContent: string): void;
117
+ /** Register a pre-parsed Recipe object. */
118
+ register(recipe: Recipe): void;
119
+ /** All loaded recipes. */
120
+ all(): readonly Recipe[];
121
+ /**
122
+ * Match a user message to the most specific recipe.
123
+ * Longest trigger phrase match wins. Returns null if no match.
124
+ */
125
+ match(userMessage: string): Recipe | null;
126
+ /**
127
+ * Format a matched recipe as a compact context block for the system prompt.
128
+ * Injected dynamically — only when the recipe matches.
129
+ */
130
+ toPromptContext(recipe: Recipe): string;
131
+ }
132
+
133
+ /**
134
+ * Load all recipe YAML files from a directory.
135
+ * Throws on validation errors — recipes should fail at load time, not runtime.
136
+ */
137
+ declare function loadRecipes(yamlDir: string): Recipe[];
138
+ /**
139
+ * Parse a single recipe from a YAML string (useful for embedded/bundled recipes).
140
+ */
141
+ declare function parseRecipe(yamlContent: string): Recipe;
142
+
8
143
  interface PendingToolCall {
9
144
  id: string;
10
145
  name: string;
@@ -328,6 +463,12 @@ interface EngineConfig {
328
463
  };
329
464
  /** Guard runner configuration (RE-2.2). Omit to disable guards. */
330
465
  guards?: GuardConfig;
466
+ /** Recipe registry for multi-step workflow guidance (RE-3.1). */
467
+ recipes?: RecipeRegistry;
468
+ /** Context budget tracking configuration (RE-3.3). */
469
+ contextBudget?: ContextBudgetConfig;
470
+ /** LLM-based summarizer for context compaction (RE-3.3). */
471
+ contextSummarizer?: (messages: Message[]) => Promise<string>;
331
472
  }
332
473
  interface LLMProvider {
333
474
  chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
@@ -445,6 +586,10 @@ declare class QueryEngine {
445
586
  private readonly costTracker;
446
587
  private readonly guardConfig;
447
588
  private readonly guardState;
589
+ private readonly recipes;
590
+ private readonly contextBudget;
591
+ private readonly contextSummarizer;
592
+ private matchedRecipe;
448
593
  private messages;
449
594
  private abortController;
450
595
  private guardEvents;
@@ -467,6 +612,8 @@ declare class QueryEngine {
467
612
  resumeWithToolResult(action: PendingAction, response: PermissionResponse): AsyncGenerator<EngineEvent>;
468
613
  interrupt(): void;
469
614
  getMessages(): readonly Message[];
615
+ getMatchedRecipe(): Recipe | null;
616
+ getContextBudget(): ContextBudget;
470
617
  reset(): void;
471
618
  getGuardEvents(): readonly GuardEvent[];
472
619
  loadMessages(messages: Message[]): void;
@@ -619,10 +766,6 @@ declare function applyToolFlags<T extends Tool>(tools: T[]): T[];
619
766
  */
620
767
  declare function getToolFlags(name: string): ToolFlags;
621
768
 
622
- interface Recipe {
623
- name: string;
624
- steps: unknown[];
625
- }
626
769
  /**
627
770
  * Routes each turn to the appropriate thinking effort level based on
628
771
  * message content, matched recipe, and session write history.
@@ -718,29 +861,6 @@ interface ConversationStateStore {
718
861
  }
719
862
  declare function buildStateContext(state: ConversationState): string;
720
863
 
721
- /** Rough token count for a message array. */
722
- declare function estimateTokens(messages: Message[]): number;
723
- interface CompactOptions {
724
- /** Max token budget for the conversation. Default 100_000. */
725
- maxTokens?: number;
726
- /** Number of recent messages to always keep uncompacted. Default 6. */
727
- keepRecentCount?: number;
728
- /** System prompt token estimate (subtracted from budget). Default 500. */
729
- systemPromptTokens?: number;
730
- }
731
- /**
732
- * Compact a conversation that exceeds the token budget.
733
- *
734
- * Strategy:
735
- * 1. Always preserve the most recent `keepRecentCount` messages (the active context).
736
- * 2. For older messages, summarise tool_result content to a brief one-liner.
737
- * 3. If still over budget, drop the oldest messages (keeping the first user message
738
- * for context continuity).
739
- *
740
- * Returns a new array — does not mutate the input.
741
- */
742
- declare function compactMessages(messages: readonly Message[], opts?: CompactOptions): Message[];
743
-
744
864
  interface McpToolDescriptor {
745
865
  name: string;
746
866
  description: string;
@@ -1546,4 +1666,4 @@ declare function clearPriceCache(): void;
1546
1666
 
1547
1667
  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.";
1548
1668
 
1549
- export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, BalanceTracker, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, 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, 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, mppServicesTool, parseMcpJson, 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 };
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 };