@t2000/engine 0.31.3 → 0.33.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 +454 -34
- package/dist/index.js +1146 -128
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.d.ts
CHANGED
|
@@ -5,9 +5,251 @@ 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 6. */
|
|
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
|
+
|
|
143
|
+
interface PendingToolCall {
|
|
144
|
+
id: string;
|
|
145
|
+
name: string;
|
|
146
|
+
input: unknown;
|
|
147
|
+
}
|
|
148
|
+
declare class TxMutex {
|
|
149
|
+
private queue;
|
|
150
|
+
private locked;
|
|
151
|
+
acquire(): Promise<void>;
|
|
152
|
+
release(): void;
|
|
153
|
+
}
|
|
154
|
+
declare function runTools(pending: PendingToolCall[], tools: Tool[], context: ToolContext, txMutex: TxMutex): AsyncGenerator<EngineEvent>;
|
|
155
|
+
|
|
156
|
+
type GuardVerdict = 'pass' | 'hint' | 'warn' | 'block';
|
|
157
|
+
type GuardTier = 'safety' | 'financial' | 'ux';
|
|
158
|
+
interface GuardResult {
|
|
159
|
+
verdict: GuardVerdict;
|
|
160
|
+
gate: string;
|
|
161
|
+
tier: GuardTier;
|
|
162
|
+
message?: string;
|
|
163
|
+
}
|
|
164
|
+
interface GuardInjection {
|
|
165
|
+
_gate: string;
|
|
166
|
+
_hint?: string;
|
|
167
|
+
_warning?: string;
|
|
168
|
+
_error?: string;
|
|
169
|
+
}
|
|
170
|
+
interface GuardCheckResult {
|
|
171
|
+
blocked: boolean;
|
|
172
|
+
blockReason?: string;
|
|
173
|
+
blockGate?: string;
|
|
174
|
+
injections: GuardInjection[];
|
|
175
|
+
events: GuardEvent[];
|
|
176
|
+
}
|
|
177
|
+
interface GuardEvent {
|
|
178
|
+
timestamp: number;
|
|
179
|
+
toolName: string;
|
|
180
|
+
toolUseId: string;
|
|
181
|
+
gate: string;
|
|
182
|
+
verdict: GuardVerdict;
|
|
183
|
+
tier: GuardTier;
|
|
184
|
+
message?: string;
|
|
185
|
+
}
|
|
186
|
+
interface GuardConfig {
|
|
187
|
+
balanceValidation?: boolean;
|
|
188
|
+
healthFactor?: {
|
|
189
|
+
warnBelow: number;
|
|
190
|
+
blockBelow: number;
|
|
191
|
+
} | false;
|
|
192
|
+
largeTransfer?: {
|
|
193
|
+
warnAbove: number;
|
|
194
|
+
strongWarnAbove: number;
|
|
195
|
+
} | false;
|
|
196
|
+
slippage?: boolean;
|
|
197
|
+
staleData?: boolean;
|
|
198
|
+
irreversibility?: boolean;
|
|
199
|
+
artifactPreview?: boolean;
|
|
200
|
+
costWarning?: boolean;
|
|
201
|
+
retryProtection?: boolean;
|
|
202
|
+
inputValidation?: boolean;
|
|
203
|
+
}
|
|
204
|
+
declare const DEFAULT_GUARD_CONFIG: GuardConfig;
|
|
205
|
+
declare class BalanceTracker {
|
|
206
|
+
private lastBalanceAt;
|
|
207
|
+
private lastWriteAt;
|
|
208
|
+
recordRead(): void;
|
|
209
|
+
recordWrite(): void;
|
|
210
|
+
isStale(): boolean;
|
|
211
|
+
hasEverRead(): boolean;
|
|
212
|
+
}
|
|
213
|
+
declare class RetryTracker {
|
|
214
|
+
private executed;
|
|
215
|
+
private key;
|
|
216
|
+
record(toolName: string, input: unknown, result: unknown): void;
|
|
217
|
+
isBlocked(toolName: string, input: unknown): {
|
|
218
|
+
blocked: boolean;
|
|
219
|
+
previousResult?: unknown;
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
declare function guardArtifactPreview(result: unknown): GuardInjection | null;
|
|
223
|
+
declare function guardStaleData(toolFlags: ToolFlags): GuardInjection | null;
|
|
224
|
+
interface GuardRunnerState {
|
|
225
|
+
balanceTracker: BalanceTracker;
|
|
226
|
+
retryTracker: RetryTracker;
|
|
227
|
+
lastHealthFactor: number | null;
|
|
228
|
+
}
|
|
229
|
+
declare function createGuardRunnerState(): GuardRunnerState;
|
|
230
|
+
declare function runGuards(tool: Tool, call: PendingToolCall, state: GuardRunnerState, config: GuardConfig, conversationContext: {
|
|
231
|
+
fullText: string;
|
|
232
|
+
lastAssistantText: string;
|
|
233
|
+
}): GuardCheckResult;
|
|
234
|
+
declare function updateGuardStateAfterToolResult(toolName: string, tool: Tool | undefined, input: unknown, result: unknown, isError: boolean, state: GuardRunnerState): void;
|
|
235
|
+
declare function extractConversationText(messages: Array<{
|
|
236
|
+
role: string;
|
|
237
|
+
content: unknown;
|
|
238
|
+
}>): {
|
|
239
|
+
fullText: string;
|
|
240
|
+
lastAssistantText: string;
|
|
241
|
+
};
|
|
242
|
+
|
|
8
243
|
type ContentBlock = {
|
|
9
244
|
type: 'text';
|
|
10
245
|
text: string;
|
|
246
|
+
} | {
|
|
247
|
+
type: 'thinking';
|
|
248
|
+
thinking: string;
|
|
249
|
+
signature: string;
|
|
250
|
+
} | {
|
|
251
|
+
type: 'redacted_thinking';
|
|
252
|
+
data: string;
|
|
11
253
|
} | {
|
|
12
254
|
type: 'tool_use';
|
|
13
255
|
id: string;
|
|
@@ -24,6 +266,12 @@ interface Message {
|
|
|
24
266
|
content: ContentBlock[];
|
|
25
267
|
}
|
|
26
268
|
type EngineEvent = {
|
|
269
|
+
type: 'thinking_delta';
|
|
270
|
+
text: string;
|
|
271
|
+
} | {
|
|
272
|
+
type: 'thinking_done';
|
|
273
|
+
signature?: string;
|
|
274
|
+
} | {
|
|
27
275
|
type: 'text_delta';
|
|
28
276
|
text: string;
|
|
29
277
|
} | {
|
|
@@ -78,6 +326,12 @@ interface PendingAction {
|
|
|
78
326
|
content: string;
|
|
79
327
|
isError: boolean;
|
|
80
328
|
}>;
|
|
329
|
+
/** Guard injections (hints/warnings) from pre-execution checks. */
|
|
330
|
+
guardInjections?: Array<{
|
|
331
|
+
_gate: string;
|
|
332
|
+
_hint?: string;
|
|
333
|
+
_warning?: string;
|
|
334
|
+
}>;
|
|
81
335
|
}
|
|
82
336
|
/**
|
|
83
337
|
* Response from the client when resolving a pending action.
|
|
@@ -132,6 +386,21 @@ interface ToolJsonSchema {
|
|
|
132
386
|
properties: Record<string, unknown>;
|
|
133
387
|
required?: string[];
|
|
134
388
|
}
|
|
389
|
+
interface ToolFlags {
|
|
390
|
+
mutating?: boolean;
|
|
391
|
+
requiresBalance?: boolean;
|
|
392
|
+
affectsHealth?: boolean;
|
|
393
|
+
irreversible?: boolean;
|
|
394
|
+
producesArtifact?: boolean;
|
|
395
|
+
costAware?: boolean;
|
|
396
|
+
maxRetries?: number;
|
|
397
|
+
}
|
|
398
|
+
type PreflightResult = {
|
|
399
|
+
valid: true;
|
|
400
|
+
} | {
|
|
401
|
+
valid: false;
|
|
402
|
+
error: string;
|
|
403
|
+
};
|
|
135
404
|
interface Tool<TInput = unknown, TOutput = unknown> {
|
|
136
405
|
name: string;
|
|
137
406
|
description: string;
|
|
@@ -141,7 +410,31 @@ interface Tool<TInput = unknown, TOutput = unknown> {
|
|
|
141
410
|
isConcurrencySafe: boolean;
|
|
142
411
|
isReadOnly: boolean;
|
|
143
412
|
permissionLevel: PermissionLevel;
|
|
413
|
+
flags: ToolFlags;
|
|
414
|
+
preflight?: (input: unknown) => PreflightResult;
|
|
415
|
+
}
|
|
416
|
+
type ThinkingEffort = 'low' | 'medium' | 'high' | 'max';
|
|
417
|
+
type ThinkingConfig = {
|
|
418
|
+
type: 'disabled';
|
|
419
|
+
} | {
|
|
420
|
+
type: 'adaptive';
|
|
421
|
+
display?: 'summarized' | 'omitted';
|
|
422
|
+
} | {
|
|
423
|
+
type: 'enabled';
|
|
424
|
+
budgetTokens: number;
|
|
425
|
+
display?: 'summarized' | 'omitted';
|
|
426
|
+
};
|
|
427
|
+
interface OutputConfig {
|
|
428
|
+
effort?: ThinkingEffort;
|
|
429
|
+
}
|
|
430
|
+
interface SystemBlock {
|
|
431
|
+
type: 'text';
|
|
432
|
+
text: string;
|
|
433
|
+
cache_control?: {
|
|
434
|
+
type: 'ephemeral';
|
|
435
|
+
};
|
|
144
436
|
}
|
|
437
|
+
type SystemPrompt = string | SystemBlock[];
|
|
145
438
|
interface EngineConfig {
|
|
146
439
|
provider: LLMProvider;
|
|
147
440
|
agent?: unknown;
|
|
@@ -152,13 +445,15 @@ interface EngineConfig {
|
|
|
152
445
|
/** Fresh on-chain position reader — called per tool invocation, bypasses MCP caching. */
|
|
153
446
|
positionFetcher?: (address: string) => Promise<ServerPositionData>;
|
|
154
447
|
tools?: Tool[];
|
|
155
|
-
systemPrompt?:
|
|
448
|
+
systemPrompt?: SystemPrompt;
|
|
156
449
|
model?: string;
|
|
157
450
|
maxTurns?: number;
|
|
158
451
|
maxTokens?: number;
|
|
159
452
|
temperature?: number;
|
|
160
453
|
/** Force tool usage on the first LLM turn (prevents text-only refusals). */
|
|
161
454
|
toolChoice?: ToolChoice;
|
|
455
|
+
thinking?: ThinkingConfig;
|
|
456
|
+
outputConfig?: OutputConfig;
|
|
162
457
|
/** Environment variables forwarded to tool context (API keys, URLs). */
|
|
163
458
|
env?: Record<string, string>;
|
|
164
459
|
costTracker?: {
|
|
@@ -166,6 +461,14 @@ interface EngineConfig {
|
|
|
166
461
|
inputCostPerToken?: number;
|
|
167
462
|
outputCostPerToken?: number;
|
|
168
463
|
};
|
|
464
|
+
/** Guard runner configuration (RE-2.2). Omit to disable guards. */
|
|
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>;
|
|
169
472
|
}
|
|
170
473
|
interface LLMProvider {
|
|
171
474
|
chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
|
|
@@ -176,12 +479,14 @@ type ToolChoice = 'auto' | 'any' | {
|
|
|
176
479
|
};
|
|
177
480
|
interface ChatParams {
|
|
178
481
|
messages: Message[];
|
|
179
|
-
systemPrompt:
|
|
482
|
+
systemPrompt: SystemPrompt;
|
|
180
483
|
tools: ToolDefinition[];
|
|
181
484
|
model?: string;
|
|
182
485
|
maxTokens?: number;
|
|
183
486
|
temperature?: number;
|
|
184
487
|
toolChoice?: ToolChoice;
|
|
488
|
+
thinking?: ThinkingConfig;
|
|
489
|
+
outputConfig?: OutputConfig;
|
|
185
490
|
signal?: AbortSignal;
|
|
186
491
|
}
|
|
187
492
|
interface ToolDefinition {
|
|
@@ -190,6 +495,16 @@ interface ToolDefinition {
|
|
|
190
495
|
input_schema: ToolJsonSchema;
|
|
191
496
|
}
|
|
192
497
|
type ProviderEvent = {
|
|
498
|
+
type: 'thinking_delta';
|
|
499
|
+
text: string;
|
|
500
|
+
} | {
|
|
501
|
+
type: 'thinking_done';
|
|
502
|
+
thinking: string;
|
|
503
|
+
signature: string;
|
|
504
|
+
} | {
|
|
505
|
+
type: 'redacted_thinking';
|
|
506
|
+
data: string;
|
|
507
|
+
} | {
|
|
193
508
|
type: 'text_delta';
|
|
194
509
|
text: string;
|
|
195
510
|
} | {
|
|
@@ -258,6 +573,8 @@ declare class QueryEngine {
|
|
|
258
573
|
private readonly maxTokens;
|
|
259
574
|
private readonly temperature;
|
|
260
575
|
private readonly toolChoice;
|
|
576
|
+
private readonly thinking;
|
|
577
|
+
private readonly outputConfig;
|
|
261
578
|
private readonly agent;
|
|
262
579
|
private readonly mcpManager;
|
|
263
580
|
private readonly walletAddress;
|
|
@@ -267,8 +584,15 @@ declare class QueryEngine {
|
|
|
267
584
|
private readonly env;
|
|
268
585
|
private readonly txMutex;
|
|
269
586
|
private readonly costTracker;
|
|
587
|
+
private readonly guardConfig;
|
|
588
|
+
private readonly guardState;
|
|
589
|
+
private readonly recipes;
|
|
590
|
+
private readonly contextBudget;
|
|
591
|
+
private readonly contextSummarizer;
|
|
592
|
+
private matchedRecipe;
|
|
270
593
|
private messages;
|
|
271
594
|
private abortController;
|
|
595
|
+
private guardEvents;
|
|
272
596
|
constructor(config: EngineConfig);
|
|
273
597
|
/**
|
|
274
598
|
* Submit a user message and stream engine events.
|
|
@@ -288,7 +612,10 @@ declare class QueryEngine {
|
|
|
288
612
|
resumeWithToolResult(action: PendingAction, response: PermissionResponse): AsyncGenerator<EngineEvent>;
|
|
289
613
|
interrupt(): void;
|
|
290
614
|
getMessages(): readonly Message[];
|
|
615
|
+
getMatchedRecipe(): Recipe | null;
|
|
616
|
+
getContextBudget(): ContextBudget;
|
|
291
617
|
reset(): void;
|
|
618
|
+
getGuardEvents(): readonly GuardEvent[];
|
|
292
619
|
loadMessages(messages: Message[]): void;
|
|
293
620
|
setServerPositions(data: EngineConfig['serverPositions']): void;
|
|
294
621
|
getUsage(): CostSnapshot;
|
|
@@ -321,6 +648,8 @@ interface BuildToolOptions<TInput, TOutput> {
|
|
|
321
648
|
call: (input: TInput, context: ToolContext) => Promise<ToolResult<TOutput>>;
|
|
322
649
|
isReadOnly?: boolean;
|
|
323
650
|
permissionLevel?: PermissionLevel;
|
|
651
|
+
flags?: ToolFlags;
|
|
652
|
+
preflight?: (input: TInput) => PreflightResult;
|
|
324
653
|
}
|
|
325
654
|
declare function buildTool<TInput, TOutput>(opts: BuildToolOptions<TInput, TOutput>): Tool<TInput, TOutput>;
|
|
326
655
|
declare function toolsToDefinitions(tools: Tool[]): {
|
|
@@ -330,20 +659,13 @@ declare function toolsToDefinitions(tools: Tool[]): {
|
|
|
330
659
|
}[];
|
|
331
660
|
declare function findTool(tools: Tool[], name: string): Tool | undefined;
|
|
332
661
|
|
|
333
|
-
interface PendingToolCall {
|
|
334
|
-
id: string;
|
|
335
|
-
name: string;
|
|
336
|
-
input: unknown;
|
|
337
|
-
}
|
|
338
|
-
declare class TxMutex {
|
|
339
|
-
private queue;
|
|
340
|
-
private locked;
|
|
341
|
-
acquire(): Promise<void>;
|
|
342
|
-
release(): void;
|
|
343
|
-
}
|
|
344
|
-
declare function runTools(pending: PendingToolCall[], tools: Tool[], context: ToolContext, txMutex: TxMutex): AsyncGenerator<EngineEvent>;
|
|
345
|
-
|
|
346
662
|
type SSEEvent = {
|
|
663
|
+
type: 'thinking_delta';
|
|
664
|
+
text: string;
|
|
665
|
+
} | {
|
|
666
|
+
type: 'thinking_done';
|
|
667
|
+
signature?: string;
|
|
668
|
+
} | {
|
|
347
669
|
type: 'text_delta';
|
|
348
670
|
text: string;
|
|
349
671
|
} | {
|
|
@@ -418,28 +740,126 @@ declare class MemorySessionStore implements SessionStore {
|
|
|
418
740
|
private evictExpired;
|
|
419
741
|
}
|
|
420
742
|
|
|
421
|
-
/** Rough token count for a message array. */
|
|
422
|
-
declare function estimateTokens(messages: Message[]): number;
|
|
423
|
-
interface CompactOptions {
|
|
424
|
-
/** Max token budget for the conversation. Default 100_000. */
|
|
425
|
-
maxTokens?: number;
|
|
426
|
-
/** Number of recent messages to always keep uncompacted. Default 6. */
|
|
427
|
-
keepRecentCount?: number;
|
|
428
|
-
/** System prompt token estimate (subtracted from budget). Default 500. */
|
|
429
|
-
systemPromptTokens?: number;
|
|
430
|
-
}
|
|
431
743
|
/**
|
|
432
|
-
*
|
|
744
|
+
* Central registry of tool flags for the guard runner (RE-2.2).
|
|
433
745
|
*
|
|
434
|
-
*
|
|
435
|
-
*
|
|
436
|
-
* 2. For older messages, summarise tool_result content to a brief one-liner.
|
|
437
|
-
* 3. If still over budget, drop the oldest messages (keeping the first user message
|
|
438
|
-
* for context continuity).
|
|
746
|
+
* Flags are declarative metadata that guards read to decide what checks to run.
|
|
747
|
+
* Read-only tools have no flags by default (empty object).
|
|
439
748
|
*
|
|
440
|
-
*
|
|
749
|
+
* Flag meanings:
|
|
750
|
+
* mutating — changes on-chain state (deposit, swap, send, borrow)
|
|
751
|
+
* requiresBalance — needs sufficient funds to execute
|
|
752
|
+
* affectsHealth — can change borrow health factor
|
|
753
|
+
* irreversible — physical mail, external transfers — can't undo
|
|
754
|
+
* producesArtifact — returns images, documents, generated content
|
|
755
|
+
* costAware — has a monetary cost the user should know about
|
|
756
|
+
* maxRetries — max calls with same input (default: unlimited for reads, 1 for writes)
|
|
757
|
+
*/
|
|
758
|
+
declare const TOOL_FLAGS: Record<string, ToolFlags>;
|
|
759
|
+
/**
|
|
760
|
+
* Apply flags from the central registry to a tool array.
|
|
761
|
+
* Tools not in the registry get empty flags (read-only tools).
|
|
762
|
+
*/
|
|
763
|
+
declare function applyToolFlags<T extends Tool>(tools: T[]): T[];
|
|
764
|
+
/**
|
|
765
|
+
* Get flags for a tool by name. Returns empty flags if not registered.
|
|
766
|
+
*/
|
|
767
|
+
declare function getToolFlags(name: string): ToolFlags;
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Routes each turn to the appropriate thinking effort level based on
|
|
771
|
+
* message content, matched recipe, and session write history.
|
|
772
|
+
*
|
|
773
|
+
* Heuristics only — no LLM call. Cost per session becomes proportional
|
|
774
|
+
* to actual query complexity rather than a fixed budget.
|
|
775
|
+
*/
|
|
776
|
+
declare function classifyEffort(model: string, userMessage: string, matchedRecipe: Recipe | null, sessionWriteCount: number): ThinkingEffort;
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Build a cacheable system prompt array from static and dynamic parts.
|
|
780
|
+
*
|
|
781
|
+
* Anthropic caches system prompt blocks marked with `cache_control: { type: 'ephemeral' }`.
|
|
782
|
+
* Static blocks (identity, tool descriptions) are cached across turns. Dynamic blocks
|
|
783
|
+
* (user profile, positions, state) change per-turn and are NOT cached.
|
|
784
|
+
*
|
|
785
|
+
* Cache breakpoints are placed at the end of each static block — Anthropic caches
|
|
786
|
+
* from the start of the prompt up to the last cache_control marker.
|
|
441
787
|
*/
|
|
442
|
-
declare function
|
|
788
|
+
declare function buildCachedSystemPrompt(staticParts: string[], dynamicPart?: string): SystemBlock[];
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Intelligence Layer prompt builders (F1, F2, F5).
|
|
792
|
+
* Pure functions — no DB or Redis dependencies.
|
|
793
|
+
* Consumed by the host app's dynamic context assembly.
|
|
794
|
+
*/
|
|
795
|
+
interface UserFinancialProfile {
|
|
796
|
+
userId: string;
|
|
797
|
+
riskAppetite: 'conservative' | 'moderate' | 'aggressive';
|
|
798
|
+
financialLiteracy: 'novice' | 'intermediate' | 'advanced';
|
|
799
|
+
prefersBriefResponses: boolean;
|
|
800
|
+
prefersExplainers: boolean;
|
|
801
|
+
currencyFraming: 'usdc' | 'fiat';
|
|
802
|
+
primaryGoals: string[];
|
|
803
|
+
knownPatterns: string[];
|
|
804
|
+
riskConfidence: number;
|
|
805
|
+
literacyConfidence: number;
|
|
806
|
+
lastInferredAt: Date | null;
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Build system prompt context from a user's financial profile.
|
|
810
|
+
* Returns empty string if profile is absent or confidence is too low.
|
|
811
|
+
* Takes the profile object directly — no DB query.
|
|
812
|
+
*/
|
|
813
|
+
declare function buildProfileContext(profile: UserFinancialProfile | null): string;
|
|
814
|
+
declare function buildProactivenessInstructions(profile: UserFinancialProfile | null): string;
|
|
815
|
+
declare function buildSelfEvaluationInstruction(): string;
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Conversation State Machine — F4 of the Intelligence Layer.
|
|
819
|
+
*
|
|
820
|
+
* Types, pure context builder, and a generic state manager interface.
|
|
821
|
+
* The Redis implementation lives in the host app (audric) since it depends on @upstash/redis.
|
|
822
|
+
*/
|
|
823
|
+
type ConversationState = {
|
|
824
|
+
type: 'idle';
|
|
825
|
+
} | {
|
|
826
|
+
type: 'mid_recipe';
|
|
827
|
+
recipeName: string;
|
|
828
|
+
currentStep: number;
|
|
829
|
+
totalSteps: number;
|
|
830
|
+
completedStepOutputs: Record<string, Record<string, string | number>>;
|
|
831
|
+
startedAt: number;
|
|
832
|
+
} | {
|
|
833
|
+
type: 'awaiting_confirmation';
|
|
834
|
+
action: string;
|
|
835
|
+
amount?: number;
|
|
836
|
+
recipient?: string;
|
|
837
|
+
proposedAt: number;
|
|
838
|
+
expiresAt: number;
|
|
839
|
+
} | {
|
|
840
|
+
type: 'post_error';
|
|
841
|
+
failedAction: string;
|
|
842
|
+
errorMessage: string;
|
|
843
|
+
occurredAt: number;
|
|
844
|
+
partialState?: string;
|
|
845
|
+
} | {
|
|
846
|
+
type: 'post_liquidation_warning';
|
|
847
|
+
healthFactor: number;
|
|
848
|
+
warnedAt: number;
|
|
849
|
+
} | {
|
|
850
|
+
type: 'onboarding';
|
|
851
|
+
sessionNumber: number;
|
|
852
|
+
hasBalance: boolean;
|
|
853
|
+
hasSavedBefore: boolean;
|
|
854
|
+
};
|
|
855
|
+
type StateType = ConversationState['type'];
|
|
856
|
+
interface ConversationStateStore {
|
|
857
|
+
get(): Promise<ConversationState>;
|
|
858
|
+
set(state: ConversationState): Promise<void>;
|
|
859
|
+
transition(to: ConversationState): Promise<void>;
|
|
860
|
+
reset(): Promise<void>;
|
|
861
|
+
}
|
|
862
|
+
declare function buildStateContext(state: ConversationState): string;
|
|
443
863
|
|
|
444
864
|
interface McpToolDescriptor {
|
|
445
865
|
name: string;
|
|
@@ -1246,4 +1666,4 @@ declare function clearPriceCache(): void;
|
|
|
1246
1666
|
|
|
1247
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.";
|
|
1248
1668
|
|
|
1249
|
-
export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_SYSTEM_PROMPT, type EngineConfig, type EngineEvent, 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 PendingAction, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionResponse, type PositionEntry, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StopReason, type SuiCoinBalance, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolJsonSchema, type ToolResult, TxMutex, WRITE_TOOLS, type WalletCoin, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, explainTxTool, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, 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 };
|